Jquery:从字符串中删除所有特定的HTML标记

我有一个包含一串文本和html标签的变量,例如:
var temp = "<div>Some text</div><p>More text<span>here</span></p><p>Even more</p>";

我想删除某种类型的所有标签.比如说所有的p和span标签.

这是我能想到的最好的:

var temp = "<div>Some text</div><p>More text<span>here</span></p><p>Even more</p>";
var $temp = $(temp);
$("p",$temp).replaceWith("foo");
alert($temp.html());  //returns "Some text"

我能找到的最接近的回答是Nick Craver的回答:strip span tags from string with jquery.

解决方法

演示: http://jsfiddle.net/VwTHF/1/
$('span,p').contents().unwrap();

.contents()获取每个此类标记内的元素和文本,.unwrap删除包装每个内容部分的元素.

根据您当前的方法,它看起来像这样:

var temp = "<div>Some text</div><p>More text<span>here</span></p><p>Even more</p>";
var $temp = $(temp);
$temp.find('span,p').contents().unwrap().end().end();

如果要继续定位原始对象,则必须使用.end()清除过滤器.

相关文章

页面搜索关键词突出 // 页面搜索关键词突出 $(function () {...
jQuery实时显示日期、时间 html: &lt;span id=&quot...
jQuery 添加水印 &lt;script src=&quot;../../../.....
中文:Sys.WebForms.PageRequestManagerParserErrorExceptio...
1. 用Response.Write方法 代码如下: Response.Write(&q...
Jquery实现按钮点击遮罩加载,处理完后恢复 思路: 1.点击按...