2012-03-29 170 views
8

我有這樣一個div:JQuery的:獲取點擊的元素的父元素ID

<div id="popupDiv1" class="popupDivClass"> 
    <a id="popupDivClose" class="popupCloseClass">x</a> 
</div> 

當我點擊「X」(我要運行名爲disablePopup(id);一個jQuery函數,其中id是在coresponding popupDiv的ID(我有許多各自與popupDiv它自己的X按鈕。

爲了做到這一點,我實現以下

$(".popupCloseClass").click(function (event) { 
    var buttonID = $(event.target).attr("id"); 
    var id = $(buttonID).closest("div").attr("id"); 
disablePopup(id); 
}); 

basicaly我得到popupCloseCl的id屁股點擊,然後我通過最接近的方法得到它的父母(相應的popupDiv)的ID。然後我調用disablePopup。

但是,這是行不通的。

我甚至嘗試使用var buttonID = $(buttonID).parent().attr("id");方法,但也沒有工作。

我也試過var id = this.id;

任何幫助是極大的讚賞

感謝

+0

'buttonID'將包含字符串' 「popupDivClose」'。如果你將它傳遞給jQuery,它將搜索所有具有**標籤名稱** popupDivClose的元素。 ID選擇器以'#'開頭。但是由於'event.target'(甚至是'this')已經指向了你想要的元素,只需使用'$(event.target).closest(...)...'或'$(this).closest (...)...'。我建議閱讀更多的jQuery教程... – 2012-03-29 08:56:20

回答

13

而不是使用closest可以使用parent這樣的...

var id = $(this).parent().attr("id"); 

通知您可以使用this關鍵字來引用拉開序幕事件的元素。就像您使用的那樣,您使用的值爲buttonID作爲元素選擇器,其值爲"popupDivClose",並且在開始時不會添加#,它不會搜索ID,而是會搜索名爲「popupDivClose」的標記元素。

如果你想使用buttonID你也可以使用下面這行代碼得到它的工作,以保持...

var id = $("#" + buttonID).parent().attr("id"); 

不過,我寧願寫像這樣整個事件......

$(".popupCloseClass").click(function (event) { 
    event.preventDefault(); 

    var id = $(this).parent().attr("id"); 

    disablePopup(id); 
}); 

通知使用event.preventDefault();這將確保瀏覽器不會處理鏈接點擊的自然動作(即頁面導航) - 雖然,在Chrome至少,你需要爲導航指定href的值反正

Here is a working example

+0

非常感謝你的明確解釋 – Youssef 2012-03-29 09:18:40

0

你應該做

$(".popupCloseClass").click(function (event) { 
    var id = $(this).closest("div").attr("id"); 
}); 

(你也可以使用$(this).parent().attr("id");),但使用最接近的情況下是安全的你改變你的html結構

+0

請注意,「parent()」將僅返回直接父級,因此選擇器參數沒有意義。你可以使用'父母(選擇器)'這將採取一個選擇器,並返回所有父母(一直在樹上)匹配選擇器 – musefan 2012-03-29 09:00:49

+0

@musefan是它毫無意義,根據我的經驗,最好使用最接近(),因爲你通常最終會修改你的html並打破​​使用parent()的代碼 – 2012-03-29 09:02:48

+0

這是一個很好的觀點,絕對值得考慮。然而,我還沒有這樣破壞我的代碼......然後我再也沒有經常使用這種功能 – musefan 2012-03-29 09:10:11

0

這工作得很好:

$('a.popupCloseClass').click(function() { 
    var id = $(this).parent().attr('id'); 
});​ 

JSFiddle Demo

你應該只使用this而不是您獲取ID的方式,然後嘗試將其用作選擇器(您錯過了# bef礦ID):

0

這必須工作:

$(".popupCloseClass").click(function (event) 
{ 
    var buttonID = $(this).parent().attr('id'); 
    disablePopup(buttonID); 
});