我想用jQuery獲取表中某行的值,當用戶點擊它時。如何使用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>
哪裏錯誤?
改變這個$(「#records_table tr」).on(「click」,function(){'to'$(「#records_table」).on(「click」,'tr',function(){' –
它的工作原理!爲什麼我的代碼不正確? –
@Alexander讓它成爲一個答案.... – epascarello