为什么我选择的数据只显示最后的数据?

时间:2018-04-15 16:06:39

标签: javascript html5 firebase firebase-realtime-database

为什么我在使用console.log

测试时无法选择第一个数据和第二个数据

这是表格: this is the table

var ref = firebase.database().ref("recommendations");

ref.on("value", function(snapshot) {
    // console.log(snapshot.val());
    var recommendations = snapshot.val();
    var keys = Object.keys(recommendations);
    console.log(keys);

for (var i = 0; i < keys.length; i++) {
    var k = keys[i];
    var title = recommendations[k].title;
    var link = recommendations[k].link;
    var presenter = recommendations[k].presenter;

    // document.getElementById('title').innerHTML = title;
    // document.getElementById('presenter').innerHTML = presenter;
    // document.getElementById('link').innerHTML = link;
    var table = document.getElementById("data");

    var tr = document.createElement('tr');
    var td1 = tr.appendChild(document.createElement('td'));
    var td2= tr.appendChild(document.createElement('td'));
    var td3 = tr.appendChild(document.createElement('td'));
    var tdEdit = tr.appendChild(document.createElement('td'));

    td1.innerHTML = title;
    td2.innerHTML = presenter;
    td3.innerHTML = link;
    tdEdit.innerHTML = "<button id='"+k+"' class='btn btn-default edit'>Edit</button>";
    table.appendChild(tr);
}

$(document).ready(function() {
    $(".edit").on("click", function(){
        console.log(k);
    })
});

});

1 个答案:

答案 0 :(得分:1)

问题是您记录了k,它是循环内部的引用。所以循环得到key0 key1 key2并保持key2,因为这是k的最后一个值。

使用类似:

$(document).ready(function() {
    $(".edit").on("click", function(){
        // From the button perspective this references the Native element.
        console.log(this.id);     // or $(this).attr("id")     
     })
});