[英]Find .closest in 'li' if not in 'div'
I'm using the closest method to find an attribute within a div: 我正在使用最接近的方法在div中查找属性:
.closest($('div[my-attribute]'));
The attribute could also exist within an li element: 该属性也可以存在于li元素中:
.closest($('li[my-attribute]'));
What is an elegant way of finding the attribute within the 'li' if it is not found in the div? 如果在div中找不到属性,那么在'li'中查找属性的优雅方法是什么?
Something like: 就像是:
var closest = myDiv.closest($('div[my-attribute]'));
if(closest == null){
closest = myDiv.closest($('li[my-attribute]'));
}
这将返回包含属性“my-attribute”的最近父母,无论天气如何,元素是div,li(或其他任何东西)。
var closest = myDiv.closest('[my-attribute]');
.closest('div[my-attribute], li[my-attribute]');
should work. 应该管用。
Do note that .closest
traverses up the dom tree, so it will only check ancestors of your base selector. 请注意
.closest
遍历dom树,因此它只会检查基本选择器的祖先。
IE: if you have a structure like this: div > ul > (li > a, li > a, li > a)
IE:如果你有这样的结构:
div > ul > (li > a, li > a, li > a)
then $("ul").closest("li")
will find nothing. 那么
$("ul").closest("li")
什么也找不到。
var closest = myDiv.closest($('div[my-attribute]')) || myDiv.closest($('li[my-attribute]'));
You can comma separate multiple selectors in jQuery. 您可以用逗号分隔jQuery中的多个选择器。
http://api.jquery.com/multiple-selector/ http://api.jquery.com/multiple-selector/
You can just use *
to select any element. 您可以使用
*
来选择任何元素。
$('*[my-attribute]')
Demo: http://jsfiddle.net/eZbN7/ 演示: http : //jsfiddle.net/eZbN7/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.