jQuery仅查找未嵌套的元素 [英] jQuery find only not nested elements

查看:51
本文介绍了jQuery仅查找未嵌套的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出此HTML结构

<div class="item">
    <div class="item">
        select me
        <div class="item">don't select me</div>
    </div>
    <span>
        <div class="item">select me</div>
    </span>
</div>

还有这个jQuery:

And this jQuery:

var firstItem = $('.item:first');
var selector = firstItem.find('.item');
selector.css('color', 'red');

我正在寻找一种仅标记firstItem div中未嵌套的.item元素的方法.这里最棘手的部分是firstItem本身已经(或可以)嵌套在.item类中.

I am looking for a way to mark only the not nested .item elements inside the firstItem div. The tricky part here is that the firstItem itself is (or can be) already nested in .item class.

我尝试了什么?

firstItem.find('.item').not('.item .item')

这不起作用,因为我们开始的第一个级别已经是.item类.而且可以将其嵌套x次,因此可以是.item .item .item .item或其他任何形式.而且起始元素没有ID,因此我也无法在选择器中使用它.

This does not work because the first level we are starting in is already an .item class. And that can be nested x times already so it could be .item .item .item .item or whatever. And the starting element does not have an ID so I cannot use that in the selector as well.

我认为解决方案应该类似于沿着DOM向下移动的 .closest()之类的东西并且不会搜索已经找到的项目的内容.

I think the solution should be something like a reversed .closest() which travels down the DOM and does not search the contents of an already found item.

在此处准备了jsFiddle: http://jsfiddle.net/LWmy3/2/

Prepared a jsFiddle here: http://jsfiddle.net/LWmy3/2/

推荐答案

尝试一下

var firstItem = $('.item:first');
$(firstItem).find(".item").each(function () {
    //console.log($(this).parent(".item")[0])
    if ($(this).parent(".item")[0] === undefined) {
        $(this).css('color', 'red')
    } else if ($(this).parent(".item")[0] != $(firstItem)[0]) {
        $(this).css('color', 'cyan')
    } else {
        $(this).css('color', 'red')
    }
});

小提琴

这篇关于jQuery仅查找未嵌套的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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