问题描述
问题:
我正在尝试使用JQuery的.find()
在元素的任何级别中查找具有给定属性的所有后代,而不是具有相同属性的那些后代的后代.
I am trying to use JQuery's .find()
to find all descendants within an element at any level that have a given attribute, but not the descendants of those descendants with the same attribute.
帮助理解:
JQuery
下面的查询的预期目标是找到元素$("#some_id")
中的所有后代(任意级别),具有some_attribute
属性,但找不到具有相同属性的后代.
The intended goal of the query below is find all descendants within element $("#some_id")
(at any level) that have some_attribute
attribute, but not the descendants of those descendants with the same attribute.
$("#some_id").find("[some_attribute]");
HTML
<span id="some_id" some_attribute>
<span some_attribute> <!-- SELECT -->
<span some_attribute> <!-- IGNORE -->
<span some_attribute> <!-- IGNORE -->
</span>
</span>
<span>
</span>
</span>
<span>
<span some_attribute> <!-- SELECT -->
<span>
<span some_attribute> <!-- IGNORE -->
</span>
</span>
<span some_attribute> <!-- IGNORE -->
</span>
</span>
</span>
<span>
<span>
<span>
<span some_attribute> <!-- SELECT -->
</span>
</span>
</span>
</span>
</span>
注意:我需要一种通用方法...我的解释会更好!假设我不知道选择器$("#some_id")
,我只有该查询的结果.还应考虑到此结果可能指向一个元素,该元素可能位于具有some_attribute
属性的另一个元素中.
NOTE: I need a generic approach... I explain better! Suppose I don't know the selector $("#some_id")
I only have the result of that query. Also consider that this result may refer to an element that may be within another element with the some_attribute
attribute.
推荐答案
这是我的解决方案.有关更多说明,请参见下面的代码注释...
Here is my solution. For more explanation see the code notes below...
// NOTE: Find all descendants at any level, but not the descendants of those descendants.
// By Questor
function findDescsNotDescsOfThose(jqPntElOrPntQry, jqFind){
var jqElInst;
if (typeof jqPntElOrPntQry === "string" ||
jqPntElOrPntQry instanceof String) {
// [Ref.: https://stackoverflow.com/a/9436948/3223785 ]
jqElInst = $(jqPntElOrPntQry);
} else {
jqElInst = jqPntElOrPntQry;
}
return jqElInst.find(jqFind)
.filter(function(){
// NOTE: We need use ".parent ()" and then ".closest ()", otherwise ".closest ()"
// will find the element itself if it fits "jqFind". By Questor
descOfjqFind = $(this).parent().closest(jqFind);
// NOTE: Checks if it is not descended from any element that also fits
// in "jqFind". Being descended from an element that also fits "jqFind"
// checks to see if this element is descended from "jqElInst". By Questor
if (descOfjqFind.length > 0 && $(descOfjqFind).
parent().closest(jqElInst).length === 1) {
return false
}
return true;
});
}
谢谢! = D
这篇关于jQuery-查找任何级别的所有后代,但找不到这些后代的后代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!