如果它们属于嵌套元素,则选择过滤它们的元素

时间:2015-02-20 06:05:23

标签: javascript jquery-selectors

我想选择具有类目标的元素。这就是我用来做的事情, $(.container).find('.target); 但是,问题是它的目标是嵌套容器的子元素。那么,如何过滤选择,以便仅定位属于当前容器元素的元素。例如,对于父'container'元素,我需要选择具有类'target'的元素,而text是'通过jquery选择它'(注意:要选择的实际元素可以包含其中的任何内容)。

HTML标记是这样的:

<div id="my-container-1" class="container" data-name="container-1">
<div class="inside-wrapper">
    <div class="inside">
        <div id="my-container-1-container-2-0" class="container" data-name="container-1:container-2">
            <div class="inside-wrapper">
                <div class="inside"></div>
                <div class="target">select this for container(my-container-1-container-2-0)</div>
            </div>
        </div>
        <div class="target">select this for container(my-container-1)</div>
    </div>
    <div class="inside">
        <div id="my-container-1-container-2-1" class="container" data-name="container-1:container-2">
            <div class="inside-wrapper">
                <div class="inside">
                    <div class="target">select this for container(my-container-1-container-2-1)</div>
                </div>
            </div>
        </div>
        <div class="maybe-other-wrapper-class">
            <div class="target">select this for container(my-container-1)</div>
        </div>
    </div>
    <div class="inside">
        <div id="my-container-1-container-2-2" class="container" data-name="container-1:container-2">
            <div class="inside-wrapper">
                <div class="inside"></div>
            </div>
        </div>
        <div class="target">select this for container(my-container-1)</div>
    </div>
    <div class="target">select this for container(my-container-1)</div>
</div>

更新:这是我当前的解决方案(jsfiddle link),它似乎正在运行,但不确定这是否是最好的方法。

var module = (function ($) {
var module = {};
//@todo This should return target elements that belong 
//to the passed container element and not parent or child container
module.getTarget = function (container) {
    return container.find('.target').filter(function () {
        return $(this).closest('.container').data('name') === container.data('name');
    });
};

$(function () {
    $('.container').each(function () {
        console.log($(this).attr('id'));
        console.log(module.getTarget($(this)));

    });
});

return module;
})(jQuery);

1 个答案:

答案 0 :(得分:0)

使用:not() selector排除嵌套.target

$('.container .target:not(.container .container .target)') 

查看此示例 - http://jsbin.com/babiviziye/1/edit?html,js,output