以下代码在Chrome / Safari中无法正常运行但在FireFox中能够正常运行的原因是什么?

$(function() {
    $('.button').on("DOMSubtreeModified",function(){
        alert("button value changed");
    });
});


是否有其他方法可以使其在其他浏览器中实现?我正在尝试检测按钮值的变化。

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


这会将突变观察者添加到您的元素。您可以配置观察者需要收听的选项。 jQuery本身不支持此功能。


  
  childList如果要观察到目标节点的子元素(包括文本节点)的添加和移除,则设置为true。
  属性如果要观察到目标属性的变异,则设置为true。
  characterData如果要观察到目标数据的变异,则设置为true。
  子树如果不仅要观察目标,还要观察目标的后代,则将其设置为true。
  attributeOldValue如果属性设置为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包含有关触发事件的很多信息,包括已添加和删除的元素。它是一个包含有关各种侦听器的数据的数组。我建议听characterDatachildList选项,因为它们表明按钮的值已更改。

07-28 02:24
查看更多