jquery - ReplaceWith() 不适用于克隆的、分离的节点

标签 jquery clone

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>');
} );


See the jsFiddle.

在这里,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/

相关文章:

ruby-on-rails - Rails 克隆对象问题

javascript - 根据 LI 单击更改 DIV 的背景图像

flash - 在 ActionScript 3 中克隆影片剪辑

java - 如何克隆TestNG的TestResult

javascript - 让几个按钮在页面刷新时保持事件状态?

android - 将相同的 ImageView 多次添加到布局

jquery - 更改 jQuery 中克隆输入元素的名称 attr 在 IE6/7 中不起作用

javascript - 使用 jQuery 计算 PRE 元素的行数

javascript - 如何在jquery中获取选定的选项卡名称

javascript - 是否可以克隆包含 javascript 的内容并维护状态?