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

Maj*_*0od 51 jquery html5

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

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

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

mar*_*eno 48

您必须观察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);
  });
});
Run Code Online (Sandbox Code Playgroud)

  • 等等,所以你的答案是没有检测到,而是在点击时触发事件?嗯 (13认同)

Shi*_*mmy 8

这样的扩展,为属性更改添加了一个事件监听器.

用法:

<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>
Run Code Online (Sandbox Code Playgroud)

将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
    }        
});
Run Code Online (Sandbox Code Playgroud)


nkr*_*ron 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;
Run Code Online (Sandbox Code Playgroud)
 <div id='foo'></div>
 
Run Code Online (Sandbox Code Playgroud)