使用var 存储元素的当前text,然后在setInverval 中检查它,并在检查后更新var 以存储当前text:
var a = $('#chat').text();
setInterval(function() {
if (a !== $('#chat').text()) { //checks the stored text against the current
alert("There has been a new message."); //do your stuff
}
a = $('#chat').text(); //updates the global var to store the current text
}, 150); //define your interval time, every 0.15 seconds in this case
Fiddle
您也可以将值存储在元素的.data() 中以避免使用全局变量。
使用.data()的示例:
$('#chat').data('curr_text', $('#chat').text());
setInterval(function() {
if ($('#chat').data('curr_text') !== $('#chat').text()) {
alert("There has been a new message.");
}
$('#chat').data('curr_text', $('#chat').text());
}, 150);
Fiddle
另一种方法,为了节省客户的内存,您可以只存储您的#chat 元素具有的子divs 的数量:
$('#chat').data('n_msgs', $('#chat').children().length);
setInterval(function() {
if ($('#chat').data('n_msgs') !== $('#chat').children().length) {
alert("There has been a new message.");
}
$('#chat').data('n_msgs', $('#chat').children().length);
}, 150);
Fiddle
编辑:这是我最后的补充,
DOM mutation event listener:
$('#chat').on('DOMNodeInserted', function() {
alert("There has been a new message.");
});
Fiddle(未在 IE
注意: 如 cmets 中所述,即使仍然支持突变事件,但由于性能损失和不同浏览器之间的一些不兼容,它们仍被归类为 deprecated by W3C,因此建议使用上述解决方案之一,仅在没有其他方法时才使用 DOM Mutation 事件。