如何在jQuery中更改包装标签? [英] How to change the wrapping tag in jQuery?
本文介绍了如何在jQuery中更改包装标签?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
以下代码行会将 p
标记更改为 div
标记:
The following line of code, will change a p
tag to a div
tag:
$('p').contents().unwrap().wrap('<div />');
以下是问题:
这也会将任何内部标签转换为 div
s!
This will also turn any inner tags into div
s as well!
示例:
采用以下HTML:
<p>abc<a>121</a>cba</p>
上面运行我的代码给了我:
Running my code above gives me this:
<div>abc</div>
<div><a>121</a></div>
<div>cba</div>
但我想实现这个目标:
<div>abc<a>121</a>cba</div>
我能做些什么来实现这一目标,为什么我的工作没有呢?
What can I do to achieve this, and why does it work when mine does not?
推荐答案
您需要
$('p').wrap('<div />').contents().unwrap();
演示:小提琴
您的代码错误,因为
-
$('p')。contents()。unwrap()
将删除p
元素并将所有子节点添加到p
元素的父元素,然后该集合有3个元素。 -
.wrap('< div / >');
将使用div
标记包装所有三个元素
$('p').contents().unwrap()
will remove thep
element and add all the child nodes to the parent ofp
element, then the set has 3 elements..wrap('<div />');
will wrap all the three elements withdiv
tag
另一种可能的解决方案是
Another possible solution is
$('p').contents().unwrap().wrapAll('<div />');
演示:小提琴
这篇关于如何在jQuery中更改包装标签?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文