gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 18:09:56 25 4
gpt4 key购买 nike

以下代码在 Chrome/Safari 中无法运行但在 FireFox 中运行良好的原因是什么?

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

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

什么事件绑定(bind)到.button 按钮值动态变化?

最佳答案

在我看来 onchange 只在输入改变时触发输入元素。由于您指的是按钮,因此输入没有改变,并且 change 事件不会触发。因此,您需要一个监视元素更改的解决方案:

对于现代浏览器,我会推荐mutation observers:

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

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

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