replaceWith()
对我来说不能正常工作。例如,给定以下 HTML:
<div id="tree1">
<div>
<h3>Item 1</h3>
<h3>Item 2</h3>
<h3>Item 3</h3>
</div>
</div>
此代码不会替换 <h3>
具有 <li>
的节点s:
var items_Bad = $("#tree1 div h3").clone ();
$("#tree1 div").remove ();
$("#tree1").append ('<ul id="Items1"></ul>');
//--- This does not replace anything!
items_Bad.replaceWith (function () {
return ('<li>' + $(this).text () + '</li>');
} );
$("#Items1").append (items_Bad);
但这段代码确实如此! :
var items_Good = $("#tree1 div h3").clone ();
$("#tree1 div").remove ();
$("#tree1").append ('<ul id="Items1"></ul>');
$("#Items1").append (items_Good);
//--- But, this works!
$("#Items1 h3"). replaceWith (function () {
return ('<li>' + $(this).text () + '</li>');
} );
在这里,replaceWith()
仅当节点(重新)附加到 DOM 时才有效,但是 the documentation说:
As of jQuery 1.4, .replaceWith() can also work on disconnected DOM nodes.
我错过了什么?
(请注意,我不控制原始页面的源。而且,我还有很多操作要做,因此过早重新附加节点来操作它们是不可取的。)
最佳答案
下面的代码是 replaceWith()
的一部分,用于处理替换分离的节点(直接取自 jQuery 1.7.1 source ,模数较小的格式差异):
replaceWith: function(value) {
if (this[0] && this[0].parentNode) {
// This deals with attached nodes...
} else {
return this.length
? this.pushStack(jQuery(jQuery.isFunction(value) ? value() : value),
"replaceWith", value)
: this;
}
}
如您所见,有两个限制阻止此代码满足您的要求:
- 所提供的函数仅调用一次,而不是集合中的每个元素调用一次,
- 在全局上下文中调用所提供的函数(即,无法通过
this
关键字使用要替换的元素)。
因此,恐怕替换分离的节点仍在进行中,您将不得不退回到第二个解决方案,直到上述限制得到解决。
关于jquery - ReplaceWith() 不适用于克隆的、分离的节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8550296/