我试图找到具有id
属性的第一个父项div
。只有在具有id属性的情况下选择父div才可以
的选择是'div .img'
,它可以是任何div嵌套
<div id='div1'>
<div id='div2'> first nested parent div
<div>second div
<img class='img' src='test.jpg'/>
</div>
</div>
<div> //this div has no id
<div>another div
<img class='img' src='cookie.jpg'/>
</div>
<div>
</div>
的选择
$('div.img')
应该输出
div2
div1
div2 shows first becasue div2 has id attribute and it is the parent of the test.img
div1 shows next becasue cookie is the second image and the first parent div that has div1 id
我已经试过里面
if($('div .img').find('.img').closest('div').attr('id')){
console.log($('div.img').closest('div').attr('id'))
}
但它不起作用。有没有办法做到这一点?非常感谢!
有没有'div'在课堂'img'您代码... – elclanrs
'div。img'不会匹配你的例子中的任何东西,看起来'div .img'就是你正在寻找的东西。 – Kapep
@kapep是我的不好。 – FlyingCat