2013-10-08 41 views
-1

HTML:Javascript [jQuery 1.9.1]獲取父div的id?

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

我想保存跨度.files的div的ID,所以我得到的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')); 

只是一個猜測,但它是returnin g未定義。

我該怎麼做?

+4

你沒有向我們展示事件發生,因此,這是什麼。 –

回答

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')) 

DEMO

$('.files').on('click', function() { 
    console.log("Sent id: " + $(this).parent().attr('id')) 
}); 
0

嘗試在第二種情況下這

alert("Sent id: " + $(".files").parent().attr('id')); 
0
console.log("Sent id: " + $(this).parent()[0].id); 

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

注意,我使用一個數組,因爲.attr可能會給你的id的數組。