简体   繁体   English

侦听DOM事件(特定属性)

[英]Listening to DOM events (specific attributes)

I need to get data when a specific attribute is added . 添加特定属性时,我需要获取数据。 I have read this post : Is there a JavaScript/jQuery DOM change listener? 我已经阅读了这篇文章: 是否有JavaScript / jQuery DOM更改监听器?

  var observer = new MutationObserver(function (mutations, observer) {
    // fired when a mutation occurs
     $.each(mutations, function(index, mutation) {

      var post = $(mutation.target).find('div[class^="ContentWrapper"]');


     });
  });
  observer.observe(document, {
    subtree: true,
    attributes: true

  });

There is a problem with this approach because there are to many events and the extension is very slow,is there an option to filter the mutations,by specific attribute? 这种方法有一个问题,因为有很多事件并且扩展很慢,是否可以根据特定属性过滤突变?

Use attributeFilter in the MutationObserverInit options. 在MutationObserverInit选项中使用attributeFilter Set it to an array of attributes that you want to listen for like so: 将其设置为要监听的属性数组,如下所示:

var attributeSpecificObserver=new MutationObserver(function_you_want_observing);
attributeSpecificObserver.observe( element_you_want_to_observe, {
    attributes: true,
    attributeFilter: ['id', 'class', 'style', 'etc'],
} );

Source: Mozilla Developer Network (MDN) . 资料来源: Mozilla开发人员网络(MDN)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM