在我看来,onchange 只会在输入更改时触发输入元素。由于您指的是按钮,因此输入不会改变,change 事件不会触发。因此,您需要一个监控元素更改的解决方案:
对于现代浏览器,我建议变异观察者:
var observer = new MutationObserver( [observer function] );
// configuration of the observer:
var config = { attributes: false, childList: true, characterData: true, subtree: true };
// pass in the target node, as well as the observer options
observer.observe(element, config);
这会为您的元素添加一个突变观察者。您可以配置观察者需要监听的选项。 Jquery 本身不支持此功能(目前)。
-
childList 如果要观察目标节点的子元素(包括文本节点)的添加和删除,则设置为 true。
attributes 如果要观察到目标属性的突变,则设置为 true。
-
characterData 如果要观察目标数据的突变,则设置为 true。
-
subtree 如果不仅要观察目标的突变,还要观察目标的后代的突变,则设置为 true。
-
attributeOldValue 如果 attributes 设置为 true,并且需要记录突变之前的目标属性值,则设置为 true。
-
characterDataOldValue 如果 characterData 设置为 true 并且需要记录突变之前的目标数据,则设置为 true。
-
attributeFilter 如果不需要观察所有属性突变,则设置为属性本地名称数组(无命名空间)。
来源:MDN
哪些浏览器支持此功能:CanIuse
在此处阅读更多信息:MDN
对于您的项目:
$(".button").each(function(){
this.observer = new MutationObserver( observeButtonChange);
// configuration of the observer:
//you can play with these.
var config = { attributes: false, childList: true, characterData: true, subtree: false};
// pass in the target node, as well as the observer options
this.observer.observe(this, config); //starts the actual observing of the element.
});
function observeButtonChange(mutations)
{
alert("Button has changed");
}
这段代码搜索页面上所有类名为.button 的元素,并使用jQuery 的each 为其附加一个Mutation Observer。每次button 的DOM 树 发生变化都会触发observeButtonChange 函数。事件对象mutations 包含很多关于触发事件的信息,包括添加和删除的元素。它是一个包含有关各种侦听器的数据的数组。我建议听一下characterData 和childList 选项,因为它们表示按钮的值发生了变化。