[英]Javascript [jQuery 1.9.1] getting the id of the parent div?
HTML:
<div id="myImages">
<div id="file_50" class="file_bg">
<span id="button_remove" class="files">Remove Image</span>
</div>
</div>
我想獲取保存span .files
的div的ID,所以我獲取ID #file_50
我嘗試過的操作:
console.log("Sent id: " + $(this).parent().attr('id'));
嘗試獲取第一個div #myImages
console.log("Sent id: " + $(this).parent().find(".file_bg").attr('id'));
只是一個猜測,但它返回的是不確定的。
我怎樣才能做到這一點?
您的代碼不起作用的原因是,當您使用parent()時,您會到達所需的對象,然后使用find查找后代。 使用parent()
或僅closest()
的就足夠了
試試這個,使用closest()
console.log("Sent id: " + $(this).closest('div.file_bg').attr('id'))
或像這樣closest('div')
console.log("Sent id: " + $(this).closest('div').attr('id'))
或者只是.parent()
console.log("Sent id: " + $(this).parent().attr('id'))
$('.files').on('click', function () {
console.log("Sent id: " + $(this).parent().attr('id'))
});
嘗試這個
alert("Sent id: " + $(".files").parent().attr('id'));
console.log("Sent id: " + $(this).parent()[0].id);
和
console.log("Sent id: " + $(this).parent().find(".file_bg")[0].id);
在第二種情況下,請注意,我正在使用數組,因為.attr
可能會為您提供ID數組。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.