我尝试使用以下代码从数组中绘制表格并从行中检索属性 id。任何建议将不胜感激。
$(document).ready(function(){
$.get('php/php.php', function(data){
$.each(data, function(index, value){
$('table').append(
"<tr id='someid'>"
+"<td>"+value.ticker+"</td>"
+"<td>"+value.bid+"</td>"
+"</tr>");
});
}, "json");
$('tr').click(function(){
var id = $(this).attr("id");
alert(id);
})
});
最佳答案
您将单击事件绑定(bind)到尚不存在的元素,因为它们是在异步回调中构造的。而不是使用 click
,使用on
。由于您的表不是动态构建的,因此您可以附加 on
处理程序。
$('table').on('click', 'tr', function () {
...
});
此外,您正在生成多个 <tr>
都具有相同的 ID;这不是有效的标记。
关于javascript - 如何在jquery和javascript中检索html标签属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11722027/