使用 jquery 删除字符串中的 span 标签
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9093838/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Remove span tag in string using jquery
提问by Ali
How to remove span tag from string using jquery? I have multiple span tag in string variable
如何使用jquery从字符串中删除span标签?我在字符串变量中有多个跨度标签
<p>No Change<span style="color: #222222;"> </span>
I love cricket<span style="color: #222222;">Cricket cricket </span></p>
回答by musefan
If this is definitely just stored as a string you can do the following...
如果这绝对只是存储为字符串,您可以执行以下操作...
var element = $(myString);//convert string to JQuery element
element.find("span").remove();//remove span elements
var newString = element.html();//get back new string
if in fact this is already rendered html in your page then just do...
如果实际上这已经在您的页面中呈现了 html,那么就做...
$("span").remove();//remove span elements (all spans on page as this code stands)
If you want to keep the contents of the span tag you can try this...
如果你想保留span标签的内容,你可以试试这个......
var element = $(myString);//convert string to JQuery element
element.find("span").each(function(index) {
var text = $(this).text();//get span content
$(this).replaceWith(text);//replace all span with just content
});
var newString = element.html();//get back new string
Here is a working example(you will see two alerts: string at start, string at end)
这是一个工作示例(您将看到两个警报:开头的字符串,结尾的字符串)
You can also just do this which might get the result you need:
您也可以这样做,这可能会得到您需要的结果:
var justText = $(myString).text();
回答by Stefan
You could try something like this;
你可以尝试这样的事情;
var theString = '<p>No Change<span style="color: #222222;"> </span>I love cricket<span style="color: #222222;">Cricket cricket </span></p>';
$(theString).wrap('<div />').find('span').remove();
...or would you like to keep it′s inner HTML?
...或者你想保留它的内部 HTML 吗?
回答by bestinamir
This way you can keep inner text of the span by using .contents() jquery method (example of my code below):
通过这种方式,您可以使用 .contents() jquery 方法(下面的代码示例)保留跨度的内部文本:
$('#navc-22 > a > span').contents().unwrap();