61

我在 HTML 中创建了一个属性,data-select-content-val它动态地填充了信息。

有没有办法检测属性值何时发生变化?

$(document).on("change", "div[data-select-content-val]", function(){
    alert("BOOP!");
});
4

3 回答 3

52

您将不得不观察 DOM 节点的变化。有一个名为 的 API MutationObserver,但看起来对它的支持非常有限。这个 SO答案有一个指向API状态的链接,但到目前为止,IE 或 Opera 似乎不支持它。

解决此问题的一种方法是让修改data-select-content-val属性的部分代码分派您可以收听的事件。

例如,请参阅:http: //jsbin.com/arucuc/3/edit了解如何将其结合在一起。

这里的代码是

$(function() {  
  // Here you register for the event and do whatever you need to do.
  $(document).on('data-attribute-changed', function() {
    var data = $('#contains-data').data('mydata');
    alert('Data changed to: ' + data);
  });

  $('#button').click(function() {
    $('#contains-data').data('mydata', 'foo');
    // Whenever you change the attribute you will user the .trigger
    // method. The name of the event is arbitrary
    $(document).trigger('data-attribute-changed');
  });

   $('#getbutton').click(function() {
    var data = $('#contains-data').data('mydata');
    alert('Data is: ' + data);
  });
});
于 2013-05-27T23:33:35.703 回答
22

您可以使用MutationObserver跟踪属性更改,包括data-*更改。例如:

var foo = document.getElementById('foo');

var observer = new MutationObserver(function(mutations) {
  console.log('data-select-content-val changed');
});
observer.observe(foo, { 
  attributes: true, 
  attributeFilter: ['data-select-content-val'] });

foo.dataset.selectContentVal = 1;
 <div id='foo'></div>
 

于 2017-04-21T16:25:38.630 回答
10

There is this extensions that adds an event listener to attribute changes.

Usage:

<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<script type="text/javascript"
  src="https://cdn.rawgit.com/meetselva/attrchange/master/js/attrchange.js"></script>

Bind attrchange handler function to selected elements

$(selector).attrchange({
    trackValues: true, /* Default to false, if set to true the event object is 
                updated with old and new value.*/
    callback: function (event) { 
        //event               - event object
        //event.attributeName - Name of the attribute modified
        //event.oldValue      - Previous value of the modified attribute
        //event.newValue      - New value of the modified attribute
        //Triggered when the selected elements attribute is added/updated/removed
    }        
});
于 2015-04-30T22:24:20.973 回答