jQuery - 动态添加元素的DomReady事件

时间:2013-09-06 09:51:34

标签: jquery dom

我正在动态加载HTML内容,特别是一个元素。由于选项数量众多,所有选项都会在JSON数组中传输到客户端,然后应由客户端的浏览器填充。 为此,我想向所有<select>元素附加一个事件,该元素会创建一堆<option>元素,并根据<select>元素中的条件选择其中一个元素。 / p>

这个JSFiddle显示了如何通过单击select元素来实现我想要的效果。但是,我想创建选项标签并在元素为DOMReady时显示所选索引 - 但我找不到适用于该事件的事件。

2 个答案:

答案 0 :(得分:0)

Change your click handler as follows.

$('#test').click(function() {
        // this select field will not be populated!
        var select = $('<select data-selected="USA" class="countrylist"></select>').appendTo("body");


        $(countries).each(function(i) {
            var option = $("<option></option>").attr("value", this.Key).text(this.Value.EnglishName);
            if (this.Key === select.data('selected')) option.prop("selected", true);
            select.append(option);
            select.get().selectedIndex = i;
        });
    });

答案 1 :(得分:0)

我设法通过在添加元素时手动调用我正在绑定的事件来找到一种方法:

// Instead of having to "click" the select fields
// I'd like to populate the <option> tags everytime a new select item is injected into the DOM.
$(document).on("click", "select.countrylist", function() {
    var select = $(this);
    $(countries).each(function(i) {
        var option = $("<option></option>").attr("value", this.Key).text(this.Value.EnglishName);
        if (this.Key === select.data('selected')) option.prop("selected", true);
        select.append(option);
        select.get().selectedIndex = i;
    });
});
// populate all existing selects
$("select.countrylist").click();

// create new select and populate it
$('#test').click(function() {
    var x = $('<select data-selected="USA" class="countrylist"></select>').appendTo("body");
    // manually trigger a click which causes populating of select
    x.click();
});

See this JSFiddle for a working example

请注意,您仍然需要将click事件绑定到$(document),而不是绑定到select(它不起作用)。

感谢您的帮助!

相关问题