【问题标题】:jQuery replaceWith not keeping the link to the element in the DOM?jQuery replaceWith 不保留指向 DOM 中元素的链接?
【发布时间】:2013-02-08 22:46:33
【问题描述】:
var el = $(this); // it's a form

在某个时候:

el.replaceWith('<p>Loading...</p>');

稍后:

el.replaceWith(output);

显然 el 在第一次 replaceWith 之后不再存在...

我可以以某种方式保留el,显然是新内容吗?

【问题讨论】:

  • 您可以使用.html() 替换元素内部而不替换元素本身。

标签: jquery html replacewith


【解决方案1】:

原来的el 已被删除并替换为replaceWith。创建一个新的引用,使用replaceWith的返回值:

var el = $(this); // it's a form
el = el.replaceWith('<p>Loading...</p>');
              //`el.replaceWith()` returns the new element
el = el.replaceWith(output);

如果您打算用新元素替换内部内容,同时保留表单,请使用:

el.html(""); //Clear html
el.append('<p>Loading...</p>');

【讨论】:

【解决方案2】:

jquery 的 replaceWith 返回被替换的元素,而不是新元素

http://api.jquery.com/replaceAll/

你应该这样做:

var el = $(this); // it's a form
var $p = $('<p>Loading...</p>');

el.replaceWith($p);

// now el is unhooked from the dom, that is el.parent() === []
// it is $p who is now hooked, check with $p.parent() === (some node)

//so you should reassing it
el = $p;

// later on

el.replaceWith(output); // but remenber, once again el is unhooked

另外,请务必检查以下问题:https://stackoverflow.com/a/892915/47633

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-02
    • 2013-06-26
    相关资源
    最近更新 更多