当用户单击它时,我想使用 jquery 获取表中一行的值。
我试过这个解决方案,但它不能正常工作:
$(document).ready(function() {
$.post("./php/myjson.php", function(data, status) {
obj = JSON.parse(data);
var trHTML = '';
for (var i = 0; i < obj.giocatori.length; i++) {
trHTML += '<tr><td><img src="../media/image/squadre/' + obj.giocatori[i].Squadra.toLowerCase() + '.png"/></td><td>'+obj.giocatori[i].Giocatore+'</td><td>' + obj.giocatori[i].Cognome + '</td><td>' + obj.giocatori[i].Prezzo + '</td></tr>';
}
trHTML+='</tbody>';
$('#records_table').append(trHTML);
});
$( "#records_table tr" ).on( "click", function( ) {
alert( $(this).find('td:nth-child(2)').html());
});
});
table tbody tr:hover {
background-color: orange;
cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="records_table" border="1">
<tbody>
<tr>
<th>Squadra</th>
<th>ID</th>
<th>Cognome</th>
<th>Prezzo</th>
</tr>
</table>
错在哪里?
最佳答案
即使表格在页面加载时存在,其内容也会在页面加载后加载(在 DOM ready
事件之后)。您想要使用委托(delegate)事件。因此,试试这个:
$( "#records_table" ).on( "click", "tr", function( ) {
alert( $('td', this).eq(2).html() );
});
注意:在添加新内容后,在 ajax 调用的成功回调中添加此部分(您的版本)也应该有效。
关于javascript - 如何使用 jquery 选择表中一行的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31547597/