jQuery ReplaceWith 不保留 DOM 中元素的链接?

发布于 2024-12-12 04:47:13 字数 291 浏览 0 评论 0原文

var el = $(this); // it's a form

在某个时候:

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

后来:

el.replaceWith(output);

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

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

var el = $(this); // it's a form

At some point:

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

Later:

el.replaceWith(output);

Apparently el doesn't exist anymore after the first replaceWith...

Can I keep somehow el, obviously with the new content ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

雨夜星沙 2024-12-19 04:47:13

原来的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>');

The original el has been removed and replaced by replaceWith. Create a new reference, using the return value of replaceWith:

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

If you intended to replace the inner content with the new element, while keeping the form, use:

el.html(""); //Clear html
el.append('<p>Loading...</p>');
望笑 2024-12-19 04:47:13

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

jquery's replaceWith returns the replaced element, not the new one

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

you should do something like this:

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

also, make sure to check this question: https://stackoverflow.com/a/892915/47633

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文