JQuery:最近的具有 ID 的 div

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5096103/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 18:34:10  来源:igfitidea点击:

JQuery: Closest div that has an ID

jqueryclosest

提问by mike

How would you write the Jquery to get the closest div that actually has an ID defined?

您将如何编写 Jquery 来获取实际定义了 ID 的最接近的 div?

回答by gor

You should use has attributeselector. This sample should do the work:

您应该使用has 属性选择器。此示例应完成以下工作:

$('selector').closest('[id]')

回答by AlfaTeK

$(elementToStart).parent().closest('div[id]');

I use the parent() to avoid just getting the element itself.

我使用 parent() 来避免只获取元素本身。

Example: http://jsfiddle.net/zQRFT/1/

示例:http: //jsfiddle.net/zQRFT/1/

回答by Martijn Pieters

Look for an id attribute on a div, using the closest method:

使用最接近的方法在 div 上查找 id 属性:

$(this).closest('div[id]');

The [id]brackets there is what's called the Has Attribute Selector

[id]那里的括号是所谓的具有属性选择器