gpt4 book ai didi

jquery - HTML 表格 onChange

转载 作者:搜寻专家 更新时间:2023-10-31 22:22:02 24 4
gpt4 key购买 nike

我有一个问题:我有一个不时通过 AJAX 脚本更新的表。此更新是从我不想更改的 Chrome 插件调用的。所以我想添加某种 jQuery 触发器,在更改表格单元格时调用我自己的函数。

这可能吗?我尝试了事件 onChange 但它不起作用(如果我是对的,它用于输入)

提前致谢!

最佳答案

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 );

jQuery 插件

如果你想将上面的 jQuery 化成你可以应用到任何元素的东西,它很容易修改:

/// 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);

显然上面是一个非常简单的版本,应该扩展它来处理监听器的添加和删除。

关于jquery - HTML 表格 onChange,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12386058/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com