我試圖找到具有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