繁体   English   中英

Javascript [jQuery 1.9.1]获取父div的ID?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM