2012-10-13 25 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