检测我所做的属性值的属性变化 [英] Detecting attribute change of value of an attribute I made

查看:87
本文介绍了检测我所做的属性值的属性变化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

<

  $(document).on(change,p>)有没有办法检测属性值的变化? div [data-select-content-val],function(){
alert(BOOP!);
});


解决方案

您必须观察DOM节点更改。有一个API称为 MutationObserver ,但看起来对它的支持非常有限。这个SO 答案包含指向状态,但似乎目前在IE或Opera中不支持它。



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



例如,请参阅: http://jsbin.com/arucuc/3/edit 如何将它们连接在一起。



这里的代码是

  $(function(){
//在这里注册活动并做任何你需要做的事。
$(文件).on('data-attribute-changed',function(){
var data = $('#contains-data')。data('mydata');
alert('Data changed to :'+ data);
});

$('#button')。click(function(){
$('#contains-data')。data('mydata','foo');
//当您更改属性时,您将使用.trigger
//方法。事件的名称是任意的
$(document).trigger('data-attribute-changed');
});
$ b $('#getbutton')。click(function(){
var data = $('#contains-data')。data('mydata');
alert('data is:'+ data);
});
});


I created an attribute in HTML data-select-content-val and it is stuffed with information dynamically.

Is there a way to detect when the attribute's value has changed?

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

解决方案

You would have to watch the DOM node changes. There is an API called MutationObserver, but it looks like the support for it is very limited. This SO answer has a link to the status of the API, but it seems like there is no support for it in IE or Opera so far.

One way you could get around this problem is to have the part of the code that modifies the data-select-content-val attribute dispatch an event that you can listen to.

For example, see: http://jsbin.com/arucuc/3/edit on how to tie it together.

The code here is

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

这篇关于检测我所做的属性值的属性变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆