使用jQuery将一个标签替换为另一个标签,保留所有属性&数据

时间:2012-12-14 02:05:52

标签: jquery

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

1 个答案:

答案 0 :(得分:0)

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

当您编写$('#myid').data('msg', 'hello world')时,内部jQuery会在名为jQuery.expando的DOM元素上创建一个特殊属性(这只是一个以"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;
}

Demo

你应该自担风险使用这个;弄乱内部通常不是最好的解决方案。

相关问题