在jQuery中选择元素时忽略子元素 [英] Ignore child elements when selecting elements in jQuery

查看:144
本文介绍了在jQuery中选择元素时忽略子元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的HTML:

<div class="foo">
    <span class="ignore_this">IGNORE THIS TEXT</span>
    SELECT THIS
</div>

我正在尝试找出如何选择foo中的所有内容,而不是选择ignore_this中的所有内容:

I'm trying to figure out how to select all the stuff inside foo, but not the stuff inside ignore_this:

$("div.foo:not(span.ignore_this)").text()

但是我不知道怎么做.

推荐答案

选择器div.foo:not(span.ignore_this)说匹配每个不是span.ignore_thisdiv.foo",这只会选择一个元素:.如果您这样重组HTML:

The selector div.foo:not(span.ignore_this) is saying "match every div.foo that isn't a span.ignore_this" which is only going to select one element: div.foo. If you restructured your html like this:

<div class="foo">
    <span class="ignore_this">IGNORE THIS TEXT</span>
    <span>SELECT THIS</span>
</div>

然后您可以致电:

$('div.foo span:not(.ignore_this)').text();

div.foo的后代(不是.ignore_this)的所有span元素匹配.

Which matches all span elements which are descendants of a div.foo that are not .ignore_this.

如果您不具备重新格式化html格式的能力,那么您可以通过额外的处理器周期来完成所需的工作:

If you don't have the luxury of reformatting the html, then you could accomplish what you want with extra processor cycles:

var clone = $('div.foo').clone();
$('span.ignore_this', clone).remove();
var text = clone.text();

这篇关于在jQuery中选择元素时忽略子元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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