2013-05-27 53 views
35

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

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

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

回答

38

您将不得不观看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); 
    }); 
}); 
+7

等那么你的答案是不检测,而是当它在点击触发事件?嗯 – ChristoKiwi

+1

@ChristoKiwi这对我来说都没有任何意义.. – Jose

6

this扩展,增加了一个事件侦听器属性更改。

用法:

<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> 

绑定attrchange处理函数选择的元素

$(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 
    }   
}); 
+0

仅供参考第二个脚本给出了“未找到” – DrLightman

+0

此链接的工作原理:https://cdn.rawgit.com/meetselva/attrchange/master/js/attrchange .js –

+0

该解决方案崩溃了Firefox和边缘,因为观察者不受支持。 –

3

您可以使用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>