Irf*_*fan 2 javascript firefox jquery google-chrome
以下代码在 Chrome/Safari 中不起作用但在 FireFox 中运行良好的原因是什么?
$(function() {
$('.button').on("DOMSubtreeModified",function(){
alert("button value changed");
});
});
Run Code Online (Sandbox Code Playgroud)
有没有其他方法可以在其他浏览器中实现这一点?我正在尝试检测按钮值的变化。
与 .button 绑定什么事件以动态更改按钮值?
在我看来, 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);
Run Code Online (Sandbox Code Playgroud)
这会向您的元素添加一个突变观察者。您可以配置观察者需要监听的选项。Jquery本身还不支持此功能。
- childList如果要观察目标节点的子元素(包括文本节点)的添加和删除,则设置为 true。如果要观察目标属性的突变,则设置为 true。
- 如果要观察目标数据的突变,则设置为 true 。
- 如果不仅要观察目标的突变,还要观察目标后代的突变,则设置为 true 。
- attributeOldValue如果属性设置为 true 并且需要记录突变之前目标的属性值,则设置为 true。
- 如果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");
}
Run Code Online (Sandbox Code Playgroud)
此代码使用类名搜索页面上的所有元素.button,并使用 jQuery将Mutation Observereach附加到它。每次DOM 树发生变化时都会触发该函数。事件对象包含有关触发事件的大量信息,包括添加和删除的元素。它是一个包含有关各个侦听器的数据的数组。我建议听一下和选项,因为它们表示按钮值的更改。buttonobserveButtonChangemutationscharacterDatachildList