在Bootstrap Modal v3.3中初始化列表

Initializing List in Bootstrap Modal v3.3x

本文关键字:初始化 列表 v3 Bootstrap Modal      更新时间:2023-09-26

我试图在Bootstrap模态中预填充列表,以便它可以从模态窗口激活时选择。它在一定程度上起作用,但当做出选择时,它并没有被认可。点击功能没有触发。它与其他已经填充的列表一起工作

HTML内部模态窗口:

  <div class="btn-group"> <a class="btn btn-default dropdown-toggle 
   btn-select" data-toggle="dropdown" href="#">Country <span class="caret">
  </span></a>
  <ul class="dropdown-menu" name="listCountry" id="listCountry"></ul>

单击未在'ListCountry'上触发的函数:

        $(".dropdown-menu li a").click(function(){
          var selText = $(this).text();
          $(this).parents('.btn-group').find('.dropdown-toggle').html(selText+'
        <span class="caret"></span>');
});

预填充列表代码:

        $('#searchModal').on('show.bs.modal', function(e){
           var countryList = $(e.currentTarget).find('#listCountry');                       
           for (i = 0; i < gSearchObject.Countries.length; i++){
            countryList.append("<li><a href='#'>" + gSearchObject.Countries[i]
            ['Country'] + "</a></li>");
    }
})

列表看起来很好,但当我选择一个项目的点击功能永远不会被触发。我找了很多其他的答案,但还没有找到一个和这个完全一样的答案。任何帮助将不胜感激!

好了,经过几个小时的修修补补,我想出了一个解决办法,虽然它工作,我不高兴。似乎触发click事件的唯一方式是元素本身预先存在。因此,我创建了一个大的虚拟条目列表,遍历它们并仅更改文本,然后删除末尾的额外条目。

代码如下:

$('#searchModal').on('show.bs.modal', function(e){
var countryList = $(e.currentTarget).find('ul#listCountry');
var el = $('#listCountry a:contains("Country")');   
if (el.length > 0){
    for (i = 0; i < el.length; i++){
        if (i >= gSearchObject.Countries.length){
            // must remove both a and li
            el[i].parentNode.parentNode.removeChild(el[i].parentNode);
        }
        else
            $(el[i]).text(gSearchObject.Countries[i]['Country']);
    }
}

})

虽然它工作,我讨厌的解决方案,并希望修复这个拼凑。谢谢。

好了,经过一番修修补补,我找到了解决方案。我的问题是,我认为这是一个引导模式的问题,当这个问题比这更孤立。当我在谷歌上搜索真正的问题时,我得到了答案,这个问题是将项目与点击功能一起添加到现有字段中。下面的链接详细解释了这一点:Click event对动态生成的元素不起作用。最重要的是。在这种情况下,"点击"功能将不起作用。解决方案如下:"您使用的click()绑定称为"直接"绑定,它只会将处理程序附加到已经存在的元素上。它不会绑定到将来创建的元素。为此,您需要使用on():"

创建一个"委托"绑定

所以这就是对我有效的解决方案。我给div指定了' countryfield '的id,并将点击功能更改为。

     $("#countryFld").on("click", ".dropdown-menu li", function(){

,一切都很好。