2012-10-13 28 views
2

我有一個從數據庫解析的JSON數組。添加onclick to json生成的表

$.getJSON(… , 

的數據與$.each然後置於由名稱爲table1的遍歷。

function(geojson) { 
    $.each(geojson.features, function(i, feature) { 
     var id = feature.properties.id; 
     var name = feature.properties.name; 
     var otherDetails = feature.properties.otherDetails; 

     // Populate table1 with clickable links 
     $("#table1 table").append('<tr><td><a href="#" onclick="['+id+']; return false;">'+name+'</a></td></tr>') 
      //populate table2 with name 
      .click(function(){ 
       $("#table2 table").append('<tr><td><a">'+name+' '+otherDetails+'</a></td></tr>') 
     }) 
    }); 
}); 

這是非常好的,正是我想要的。 表中的每個功能「名稱」都是可點擊的,我希望在單擊時爲另一個表(table2)填充「name」和「otherDetails」以僅記錄一條記錄。 上面的代碼幾乎讓我在那裏,但打算填充table2與單擊的功能的名稱,它填充table2與完整的功能幾乎table1副本陣列,我認爲,因爲它仍然在$.each內。 如何停止嵌套append中的每個迭代? 在此先感謝。

回答

0

向table1的行添加點擊處理程序。點擊後,拉出名稱放入table2的新行。

$('#table1 table').on('click', 'tr', function() 
{ 
    var name = $(this).find('a').text(); 
    $('#table2 table').append('<tr><td><a">' + name + '</a></td></tr>'); 
}); 

更改維護數據的方法是使用data attributes。這將允許您也使用其他信息數據。

1

click事件處理程序在table級別重複應用。嘗試應用它到行,像這樣:

// Populate table1 with clickable links 
var newRow = $('<tr><td><a href="#" onclick="['+id+']; return false;">'+name+'</a></td></tr>'); 
$("#table1 table").append(newRow); 
$(newRow).click(function(){ 
    $("#table2 table").append('<tr><td><a">'+name+' '+otherDetails+'</a></td></tr>') 
}); 
+0

工作就像一個魅力,thx! – Bwyss