选择动态添加的元素

时间:2013-04-28 18:17:48

标签: jquery

我正在尝试从mysql异步加载数据。首先,在页面加载时,我向页面添加了多个div:

$(document).ready(function(){
        // Layout
        var main = $("#main-div");
        for(var i = 0; i < array.length; ++i) {
            main.append("<div class='container'><a href=\"blah\">"+array[i]+"</a><div class='button-container'><span id='playcount_"+array[i]+"' class='playcount' style='margin-right:5%'>nope</span></div></div>");
        }
        // Get info for each sound in array
        for(var i = 0; i < array.length; ++i) {
            $.post("script/php_getinfo.php", { "file": array[i] }, updatePlaycount, "json");
        }
});

container div添加了span,其ID为playcount_Aplaycount_B等。添加div后,POST为对数组中的每个项目进行制作,并在成功时调用updatePlaycount

updatePlaycount尝试选择元素并将文本插入span

function updatePlaycount(data) {
    $('#playcount_'+data.name).text(data.playcount);
}

该函数正确获取data.namedata.playcount字段(例如A1),但由于某种原因,jQuery无法找到#playcount_A!当然他们已经被添加了,因为添加divs没有任何负载...

1 个答案:

答案 0 :(得分:2)

它对我有用。似乎没有那么多代码来演示。 fiddles可以使用ajax,所以如果你有一个(大)库可以包含你也可以这样做

<强> DEMO

$(document).ready(function () {
    // Layout
    var main = $("#main-div"),
        array = ["A", "B", "C"],
        updatePlaycount =  function (data) {
                console.log(data);
                var $playct = $('#playcount_' + data.name);
                console.log($playct);
                $playct.text(data.playcount);
            }

    function ajaxI(i,arr){
      var J=  JSON.stringify({
                    "name": arr[i],
                        "playcount": (i+1)+''
                });
        console.log(J)
    $.ajax({
            type : "POST",
            dataType: "json",
            url: "/echo/json/",
            data: {
                json: J,
                delay: 3
                },
            success:  updatePlaycount
        });
    }

    for (var i = 0; i < array.length; ++i) {
        main.append("<div class='container'><a href=\"blah\">" + array[i] + "</a><div class='button-container'><span id='playcount_" + array[i] + "' class='playcount' style='margin-right:5%'>nope</span></div></div>");
    } // end for

    // Get info for each sound in array
    for (var j = 0; j < array.length; ++j) {
       ajaxI(j,array);
    } // end for
}); // end ready

请将支票寄至...... j / k