0

我正在尝试从 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 时,spanid 为playcount_A,playcount_B等。添加 div 后,会POST为数组中的每个项目创建 a 并调用updatePlaycount成功。

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

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

该函数正确获取data.nameanddata.playcount字段(例如Aand 1),但由于某种原因 jQuery 找不到#playcount_A!当然它们已经被添加了,因为添加 div 不涉及加载......

4

1 回答 1

2

这个对我有用。演示的代码似乎不多。顺便说一句,小提琴可以使用 ajax,所以如果你有一个(大)库要包含,你也可以这样做

演示

$(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

于 2013-04-29T15:50:27.450 回答