JQuery find()带有忽略特定标签及其子代的选项

时间:2017-05-01 11:58:07

标签: javascript jquery

我需要一个jQuery函数,根据它们的属性,在搜索时忽略(过滤掉)特定标记及其所有(大)子元素。 更具体:我想找到具有属性data-type =" a"的标签,但仅当其中一个(大)父母没有属性data-type =" b& #34 ;. 我想这不存在,我应该编写自己的javascript代码进行搜索。我倾向于这样做,但我读到这是容易出错而且不兼容浏览器?

3 个答案:

答案 0 :(得分:3)

jQuery提供了一种方法来完成这种称为.grep()的事情(参见docs

var aTypes = $('[data-type="a"]')

aTypes = $.grep(aTypes, function(el, i) {
  return $(el).parents('[data-type="b"]').length === 0
})

console.log(aTypes)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div data-type="a"></div>
<div data-type="a">
  <div data-type="b"></div>
</div>
<div data-type="b"></div>
<div data-type="b">
 <div data-type="a">Ignore Me</div>
</div>
<div data-type="a">
  <div data-type="a"></div>
</div>

答案 1 :(得分:1)

var aTypes = $('[data-type="a"]');
var aTypesToKeep = [];
$.each(aTypes, function() {
    var hasBType = $(this).parents().every(function(el) {
        return $(this).attr('data-type') === 'b';
    });
    if (!hasBType) {
        aTypesToKeep.push($(this));
    } 
});
// aTypesToKeep array with jQuery elements of data-type a that don't have parent with data-type b

答案 2 :(得分:0)

我最终使用$ .filtter()和$ .parentsUntil()。 以下是某人使用它的一般功能:

// returns found jquery tag(s), jquery object
function FindWithFilterOut($ctlMain, filterIn,

    // any controls that have these properties are filtered out of search and all their children
    // to define multiple filters combined with OR operator use selectors separated with comma, for excample: [data-type='a'],[data-type='c'] 
    filterOut

    ) {
    return $ctlMain.find(filterIn).filter(function (index) {
        var $parentToFilterOut = $(this).parentsUntil($ctlMain, filterOut);
        if ($parentToFilterOut.length > 0)
            return false;
        if ($(this).is(filterOut))
            return false;
        return true;
    });
}

https://jsfiddle.net/tskoda/80s9d61s/3/