在jQuery中,我可以将“closest”或“parents()”与“hasClass”结合使用,以便在页面上存在给定类的最接近元素,如果存在的话?
var matchingDiv = $(this).closest('div').hasClass('SomeClass')
if ( matchingDiv != null )
{
//we found matching element now manipulate it
}
我将始终拥有一个匹配的 div 元素,或者没有。
谢谢。
if (matchingDiv.length)
,因为0会被评估为false
。 - Doug Neiner