我有一个问题:我有一个不时由 AJAX 脚本更新的表。此更新是从我不想更改的 Chrome 插件调用的。所以我想添加某种 jQuery 触发器,在更改表格单元格时会调用我自己的函数。
是否可以?我尝试了事件 onChange 但它不起作用(如果我是对的,它是用于输入)
提前致谢!
使用 setInterval() 您可以不断地监控您的表格的内容并将其与之前的内容进行比较。如果内容不同,则表已更改。
$(function() {
var previous = $("#mytable").text();
$check = function() {
if ($("#mytable").text() != previous) {
myOwnFunction();
}
previous = $("#mytable").text();
}
setInterval(function() { $check(); }, 1000);
}
function myOwnFunction() {
alert("CHANGED");
}
onchange
设计用于与输入类似<select>
- 所以在这种情况下不会工作。您可以使用特定的 dom 相关事件(例如DOMSubtreeModified
),但这些不是跨浏览器并且具有不同的实现(它们甚至现在可能已被弃用):
http://en.wikipedia.org/wiki/DOM_events
MutationEvents
如上所述,似乎已经被MutationObservers
我自己还没有使用过的东西所取代......但听起来它会满足你的需要:
http://dvcs.w3.org/hg/domcore/raw-file/tip/Overview.html#mutation-observers
除此之外,您可以回退到一个setInterval
处理程序,该处理程序将侦听目标元素中 HTML 的任何变化......当它发生变化时,您会触发一个函数。
function watch( targetElement, triggerFunction ){
/// store the original html to compare with later
var html = targetElement.innerHTML;
/// start our constant checking function
setInterval(function(){
/// compare the previous html with the current
if ( html != targetElement.innerHTML ) {
/// trigger our function when a change occurs
triggerFunction();
/// update html so that this doesn't keep triggering
html = targetElement.innerHTML;
}
},500);
}
function whenChangeHappens(){
alert('this will trigger when the html changes in my_target');
}
watch( document.getElementById('my_target'), whenChangeHappens );
如果你想 jQueryify 上面的东西,你可以应用到任何元素上,它很容易修改:
/// set up the very simple jQuery plugin
(function($){
$.fn.domChange = function( whenChanged ){
/// we want to store our setInterval statically so that we
/// only use one for all the listeners we might create in a page
var _static = $.fn.domChange;
_static.calls = [];
_static.iid = setInterval( function(){
var i = _static.calls.length;
while ( i-- ) {
if ( _static.calls[i] ) {
_static.calls[i]();
}
}
}, 500 );
/// step each element in the jQuery collection and apply a
/// logic block that checks for the change in html
this.each (function(){
var target = $(this), html = target.html();
/// by adding the function to a list we can easily switch
/// in extra checks to the main setInterval function
_static.calls.push (function(){
if ( html != target.html() ) {
html = target.html();
whenChanged();
}
});
});
}
})(typeof jQuery != undefined && jQuery);
/// example code to test this
(function($){
$(function(){
$('div').domChange( function(){
alert('I was changed!');
} );
});
})(typeof jQuery != undefined && jQuery);
显然上面是一个非常简单的版本,应该扩展它来处理监听器的添加和删除。