jQuery:删除 HTML 元素,同时保留其子元素
我想像这样添加 HTML:
<div><img src="item.png"/> <a href="#"><span>Hello</span></a></div>
但在某些情况下,我需要摆脱包装 a 元素,所以它看起来像这样:
<div><img src="item.png"/> <span>Hello</span></div>
这个 a 元素可以位于任意 HTML 片段中的任何位置。我通过[href="#"]抓住它。该 HTML 不是 DOM 的一部分,它是在删除 a 元素后添加到 DOM 中的。
我尝试了 jQuery 为此提供的所有东西,但没有成功。我的主要问题是, 似乎没有办法将选择器应用到由 jQuery 创建的 HTML,如下所示:
$("html code from above");
我试图让 a 元素用它的内部 HTML 替换它,但我所有的构造都是 find() 和replaceWith() 失败,大多只剩下Hello
:(
jQuery-pro 如何解决这个问题?
I want to add HTML like this:
<div><img src="item.png"/> <a href="#"><span>Hello</span></a></div>
but in some cases I need to get rid of the wrapping a-element, so it looks like this:
<div><img src="item.png"/> <span>Hello</span></div>
This a-element could be anywhere in arbitrary HTML-fragments. I grab it by a[href="#"]. This HTML is not part of the DOM, it get's added to the DOM after the a-element was removed.
I went to all kind of stuff jQuery offers for this, but didn't make it. My main problem is,
that there seems to be no way to apply a selector to HTML created by jQuery like this:
$("html code from above");
I tried to get the a-element replacing it with it's inner HTML, but all my constructs with
find() and replaceWith() fail, mostly just the <span>Hello</span>
is left :(
How does a jQuery-pro solve this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
unwrap 功能不会满足您的要求吗?
如果您只想删除周围的标签(如锚点)
Wouldn't the unwrap feature do what you want?
If you just want to remove the surrounding tag (like an anchor)
您需要做的是设置选择器的上下文。请参阅此参考:http://api.jquery.com/jquery/#selector-context
在您的情况下,当您选择替换链接时,请将上下文设置为您正在修改的 HTML 片段。这是一个示例:
这是一个实际演示(不是很令人兴奋,但表明它有效): http: //jsfiddle.net/Ender/dQ32B/
What you need to do is set the context of your selector. See this reference: http://api.jquery.com/jquery/#selector-context
In your case, when you do the selection to replace the link, set the context as the HTML fragment that you are modifying. Here's an example:
And here's a demo of that in action (not very exciting, but shows that it works): http://jsfiddle.net/Ender/dQ32B/