javascript - 突变观察者可以监听 "data-"属性的变化吗?

标签 javascript jquery dom mutation-observers

所以问题是我有一个 html 元素,它在“data-”属性中有一个对象(通过 jQuery ofc 设置),我想监听该属性的变化。

我已经尝试了很多事情,比如在 MutationObserverInit object 中设置几乎所有可能的组合值,但这些都没有帮助。

有人知道这是否可行吗?

$('#some-id').click( function() {
  //$('#some-id').attr('title', 'some-title'); //this works
  $('#some-id').data('foo', 'bar1'); //this don't
});

var functionCallBack = function(mutations) {
  alert('something changed')
}

// select the target node
var target = document.getElementById("some-id");

// create an observer instance
var observer = new MutationObserver(functionCallBack);

// configuration of the observer:
var config = { subtree: true, childList: true , attributes: true};

// pass in the target node, as well as the observer options
observer.observe(target, config);

$('#some-id').data('foo', 'bar');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="some-id">HEY</div>

最佳答案

新答案(基于 Oriol's Answer ):

我认为 Oriol 提供了更好的方法,但还可以进一步优化。

var object = {
  'key': 'value'
};

$('.addObj').click(function() {
  $('#some-id').observeData('foo', object, function() {
    console.log("Object Added");
  });
});

$('.removeObj').click(function() {
  $('#some-id').observeData('foo', null, function() {
    console.log("Object removed");
  });
});


jQuery.fn.observeData = function(name, object, callback) {
  // Get elemenet
  var element = $(this[0]);

  // Add data
  element.data(name, object);

  // Call the callback function
  callback();

  // Return this for a chainable function
  return this;
};
span {
  padding: 10px;
  float: left;
  margin: 5px;
  cursor: pointer;
  background-color: green;
  border: 1px solid black;
  border-radius: 5px;
  transition: all 0.5s;
  color: white;
  font-size: 13px;
}
span:hover {
  opacity: 0.8;
}
#some-id {
  text-align: center;
  width: 100%;
  margin: 10px 0;
  font-size: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="some-id">HEY</div>

<span class='addObj'>Add Object</span>
<span class='removeObj'>Remove Object</span>

JSFiddle:https://jsfiddle.net/t012rb9j/1/

旧答案:

正如您在代码中所述:

$('#some-id').click(function() {

 // $('#some-id').attr('title', 'some-title'); //this works
 $('#some-id').data('foo', 'bar1'); //this don't
});

.attr() 有效,而 .data() 无效。原因是 .attr() 向您的 HTML 标记添加属性值,而 data存储此数据在内存中。

来自 jQuery 文档:

.data(): Store arbitrary data associated with the specified element and/or return the value that was set.

.attr(): Get the value of an attribute for the first element in the set of matched elements or set one or more attributes for every matched element.

检测数据更改的一种方法(如果您想存储对象)是将这两个函数结合起来。

var object = {
  'key': 'value'
};

$('.addObj').click(function() {
  $('#some-id').data('foo', object).attr("data-attached", "true");
});

$('.removeObj').click(function() {
  $('#some-id').data('foo', null).attr("data-attached", "false");
});


var functionCallBack = function(mutations) {
  mutations.forEach(function(mutation) {
    if (jQuery(mutation.target).attr("data-attached") == "true") {
      // Your code here
      console.log("Object Added");
    } else {
      console.log("Object removed");
    }
  });
}

// select the target node
var target = document.getElementById("some-id");

// create an observer instance
var observer = new MutationObserver(functionCallBack);

// configuration of the observer:
var config = {
  subtree: true,
  childList: true,
  attributes: true
};

// pass in the target node, as well as the observer options
observer.observe(target, config);
.addObj, .removeObj {
  padding: 10px;
  float: left;
  margin: 5px;
  cursor: pointer;
  background-color: green;
  border: 1px solid black;
  border-radius: 5px;
  transition: all 0.5s;
  color: white;
  font-size: 13px;
}

.addObj:hover, .removeObj:hover {
  opacity: 0.8;
}

#some-id {
  text-align: center;
  width: 100%;
  margin: 10px 0;
  font-size: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="some-id">HEY</div>

<span class='addObj'>Add Object</span>
<span class='removeObj'>Remove Object</span>

JSFiddle:https://jsfiddle.net/9xkb6jv4/

关于javascript - 突变观察者可以监听 "data-"属性的变化吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41538686/

相关文章:

javascript - 对于异步内部函数,外部函数的函数参数是否会发生变化?

javascript - 如何使用 Breeze 导航属性对 knockout 中的 html 表进行排序?

javascript - 无法使用 javascript 解析 xml DOM(从文件)

javascript - 检测输入 (type=text) 元素中的文本是否超出 FireFox 中的边界

javascript - ajax 成功时重置所有字段(表单)

javascript - Bootstrap JS 验证器和表单提交

javascript - 使用 jquery.load 加载多个 Highcharts

javascript - 使用 winjs.promise 实现 .done().fail() 方法

javascript - 如何在javascript中使用数组获取和设置html标签的值?

ios - iOS "mobile web app"中的 location.reload(true) 在 safari 中重新打开