检测我所做的属性值的属性变化

时间:2013-05-27 23:25:37

标签: jquery html5

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

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

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

3 个答案:

答案 0 :(得分:43)

您必须观察DOM节点的更改。有一个名为MutationObserver的API,但看起来它的支持非常有限。这个SO answer有一个指向API的status的链接,但到目前为止似乎在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);
  });
});

答案 1 :(得分:6)

您可以使用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>
 
&#13;
&#13;
&#13;

答案 2 :(得分:0)

以上所有答案在2018年都不正确。其中一些原因是因为它们实际上并未绑定到事件,而是尝试手动调用该事件(???),其他原因是因为它们不使用本机jQuery和而是使用扩展名。

原生jQuery解决方案是:

$("#element-to-observe").bind('change', function(event) {
   alert( 'The value has been changed to '+$("#element-to-observe").attr("value") );
});

$(document).ready(function(){
   $("#element-to-observe").change(function(){
      alert('The value has been changed to '+ $("#element-to-observe").attr("value") );
   });
});
相关问题