jQuery,从字符串中删除元素 [英] JQuery, remove element from string

查看:611
本文介绍了jQuery,从字符串中删除元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串:

var s = '<h1>heading</h1><p>para</p>';

,我想从中删除h1元素. 我已经尝试过:

and I want to remove the h1 element from it. Ive tried:

$(s).remove('h1');

,但s仍包含h1元素 我也尝试过:

but s still contains the h1 element Ive also tried:

s = $(s).remove('h1');

$('h1', s).remove();

$('h1', $(s)).remove();

等等等

有什么想法吗?

推荐答案

更新:我看到您刚刚更改了问题.现在的解决方案是这样:

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);​

尝试一下: http://jsfiddle.net/q9crX/19/

因为您现在在jQuery对象中具有多个顶层"元素,所以可以使用.not()(基本上与.filter()相反)来删除h1.

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.

这与$(s).filter(':not(h1)');

  • http://api.jquery.com/not/
  • http://api.jquery.com/filter/

原始答案

$(s).find('h1').remove();

因此,如果要将结果附加到body,则可以执行以下操作:

So if you were to append the result to the body, you could do:

var s = '<div><h1>heading</h1><p>para</p></div>';

var $s = $(s).find('h1').remove().end();

$('body').append($s);​

尝试一下: http://jsfiddle.net/q9crX/

这篇关于jQuery,从字符串中删除元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆