2

我意识到这类似于Using jQuery to replace one tag with another,但是我希望用 html 中的另一个标签替换一个标签,但保留对象的属性和任何定义的自定义数据(通过 $.data 设置)。知道如何实现这一目标吗?

4

1 回答 1

0

复制属性应该不会太难,这个答案的重点是保留附加到节点的数据和事件。

当您编写 时$('#myid').data('msg', 'hello world'),jQuery 会在内部为 DOM 元素创建一个特殊属性,称为jQuery.expando(它只是一个以一串数字开头"jQuery"并后跟一串数字的字符串)。该属性的值包含jQuery.cache数组的键,这是您的自定义数据和事件处理程序存储的位置。

// lets assume you want to replace node a with node b
// we need the DOM elements for this
var nodea = ..., nodeb = ...;

// jQuery data references are stored in a special property of the node
var key = nodea[jQuery.expando], 
cache = jQuery.cache[key];

// perform replacement
$(nodea).replaceWith(nodeb);

if (cache) {
  // restore data
  jQuery.cache[key] = cache;
  nodeb[jQuery.expando] = key;
}

演示

不过,您应该自担风险使用它;搞乱内部通常不是最好的解决方案。

于 2012-12-14T02:50:44.720 回答