在jquery中,我可以将“closest”或Parents()与“hasClass”结合起来,这样它就会给我一个与给定类最接近的元素(如果页面上存在的话)?
var matchingDiv = $(this).closest('div').hasClass('SomeClass')
if ( matchingDiv != null )
{
//we found matching element now manipulate it
}
我总是要么有一个匹配的 div 元素,要么没有。 谢谢。
最佳答案
var matchingDiv = $(this).closest('div.SomeClass')
if ( matchingDiv.length )
{
// use length to find if there was a match.
// closest() will always return an object.
}
如果这不起作用,也许可以发布一些 html。也许那里有问题?
关于jquery hasClass 匹配元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2224385/