-1

HTML:

<div id="myImages">
    <div id="file_50" class="file_bg">
        <span id="button_remove" class="files">Remove Image</span>
    </div>
</div>

我想获取包含 span 的 div 的 id .files,所以我得到了 id#file_50 我尝试过的内容:

console.log("Sent id: " + $(this).parent().attr('id'));

此尝试正在获取第一个 div 的 id,#myImages

console.log("Sent id: " + $(this).parent().find(".file_bg").attr('id'));

只是一个猜测,但它返回未定义。

我怎样才能做到这一点?

4

3 回答 3

4

您的代码不起作用的原因是,当您使用 parent() 时,您会得到您想要的对象,然后您正在使用 find 来搜索后代。足以使用parent()或只是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'))
 });
于 2013-10-08T14:14:16.313 回答
0

尝试这个

alert("Sent id: " + $(".files").parent().attr('id'));
于 2013-10-08T14:16:08.247 回答
0
console.log("Sent id: " + $(this).parent()[0].id);

console.log("Sent id: " + $(this).parent().find(".file_bg")[0].id);

注意第二种情况,我使用的是数组,因为.attr可能会给你一个 id 数组。

于 2013-10-08T14:18:57.303 回答