所以我正在尝试做的是,每次表格的顶行发生变化时都会执行警报。问题是,我每隔10秒重新生成一次HTML,所以我无法弄清楚如何“监听”变化。
<table id="theTable">
<th>Id</th>
<th>Name</th>
<th>Score</th>
<tr>
<td>1</td>
<td>James</td>
<td>50</td>
</tr>
<tr>
<td>2</td>
<td>Peter</td>
<td>25</td>
</tr>
<tr>
<td>3</td>
<td>Sally</td>
<td>10</td>
</tr>
</table>
$("#theTable").on("change", function() {
alert("This person took the lead");
});
//Goal: An alert every time someone new takes the lead. The problem is, at this point - the table HTML is regenerated every 10 seconds (it will be better solution soon), so it's kind of hard to "listen for changes".
我在想什么: 1.在页面加载时,查看第一个表行并保存用户ID的值,下次重新生成HTML时,运行比较?
答案 0 :(得分:9)
您需要首先将自定义事件绑定到表:
// table listening to an "update" custom event
$('#leaderboard-spot').on('update', function(){
alert('Table updated, launching kill space goats sequence now.')
});
当您的ajax请求成功并且您的表已更新时,请在桌面上触发自定义事件:
function loadLeaderboard() {
var competitionId = $("body").attr("data-competitionId");
var url = "leaderboard_api.php?competitionId=" + competitionId;
$.get(url, function (data) {
$("#leaderboard-spot").html(data);
// manually triggering an update
$("#leaderboard-spot").trigger('update');
});
}