javascript - $ ('.button' ).on ("DOMSubtreeModified") 在 chrome/safari 中不起作用,但在 Firefox 中起作用

标签 javascript jquery google-chrome firefox

下面的代码在 Chrome/Safari 中不起作用但在 FireFox 中运行良好的原因是什么?

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

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

要与 .button 绑定(bind)什么事件才能动态更改按钮值?

最佳答案

在我看来,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 Set to true if additions and removals of the target node's child elements (including text nodes) are to be observed. attributes Set to true if mutations to target's attributes are to be observed.
  • characterData Set to true if mutations to target's data are to be observed.
  • subtree Set to true if mutations to not just target, but also target's descendants are to be observed.
  • attributeOldValue Set to true if attributes is set to true and target's attribute value before the mutation needs to be recorded.
  • characterDataOldValue Set to true if characterData is set to true and target's data before the mutation needs to be recorded.
  • attributeFilter Set to an array of attribute local names (without namespace) if not all attribute mutations need to be observed.

Source: 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 附加到它。每次按钮DOM树发生变化时,都会触发observeButtonChange函数。事件对象mutations包含有关触发事件的大量信息,包括添加和删除的元素。它是一个包含有关各种监听器的数据的数组。我建议监听 characterDatachildList 选项,因为它们指示按钮值的更改。

关于javascript - $ ('.button' ).on ("DOMSubtreeModified") 在 chrome/safari 中不起作用,但在 Firefox 中起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28380078/

相关文章:

javascript - jquery for 循环在对话框 div 按钮单击中不起作用

java - AES 加密 java 和 javascript 不同的输出

jquery水平滑动与动态内容

javascript - 在 div 中禁用 html

jquery count 选择与所需值匹配的输入

html - 在 Chrome 中, 'span' 元素内嵌套的 'a' 元素在悬停时比链接的其余部分转换颜色慢

javascript - AJAX 表单不显示成功或错误消息

javascript - 使用 Javascript 从链接中删除不需要的 CSS

apache - Chrome 上的虚拟主机因隐私错误而被阻止

css - 在某些浏览器中,如何去掉文本框控件右下角的小人字形