JQuery,从字符串中删除元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3331449/
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
JQuery, remove element from string
提问by Petah
I have a string:
我有一个字符串:
var s = '<h1>heading</h1><p>para</p>';
and I want to remove the h1
element from it.
Ive tried:
我想从中删除h1
元素。我试过了:
$(s).remove('h1');
but s still contains the h1
element
Ive also tried:
但 s 仍然包含h1
我也尝试过的元素:
s = $(s).remove('h1');
and
和
$('h1', s).remove();
and
和
$('h1', $(s)).remove();
etc etc etc
等等等等
Any ideas?
有任何想法吗?
回答by user113716
Update: I see you just changed the question. Now the solution would be this:
更新:我看到你刚刚改变了问题。现在的解决方案是这样的:
var s = '<h1>heading</h1><p>para</p>';
var $s = $(s).not('h1');
$('body').append($s);?
Try it out:http://jsfiddle.net/q9crX/19/
试试看:http : //jsfiddle.net/q9crX/19/
Because you now have more than one "top level" element in the jQuery object, you can use .not()
(which is basically the opposite of .filter()
) to remove the h1
.
因为您现在在 jQuery 对象中有多个“顶级”元素,您可以使用.not()
(基本上与 相反.filter()
)删除h1
.
It would be the same as doing $(s).filter(':not(h1)');
这和做一样 $(s).filter(':not(h1)');
Original answer
原答案
$(s).find('h1').remove();
So if you were to append the result to the body
, you could do:
因此,如果要将结果附加到body
,则可以执行以下操作:
var s = '<div><h1>heading</h1><p>para</p></div>';
var $s = $(s).find('h1').remove().end();
$('body').append($s);?
Try it out:http://jsfiddle.net/q9crX/
试试看:http : //jsfiddle.net/q9crX/