2013-02-08 94 views
1

所以,我有幾個表使用基於類的jQuery進行迭代,但是我的行爲需要稍微改變,具體取決於我所處元素的ID。下面是我的代碼:需要獲得當前元素的ID

<table id="Brokers" class="nodeTable" border=1 /> 
<table id="Controllers" class="nodeTable" border=1 /> 
<table id="Cluster-Drivers" class="nodeTable" border=1 /> 

jQuery(".nodeTable").html(nodeHealthTable({ 
    Role: jQuery(this).attr("id") 
})) 

這最終將使用空字符串填充角色。我如何訪問當前元素的ID?

回答

4

this在代碼不是指所選擇的元件,html方法接受一個函數,這個函數this的上下文中是指當前元素(jQuery使用each方法在內部)。

jQuery(".nodeTable").html(function() { 
    return nodeHealthTable({ Role: this.id }); 
}) 
+0

真棒,完美的工作,謝謝你! – Kreg 2013-02-08 23:36:48

+0

@Kreg歡迎您。 – undefined 2013-02-08 23:39:17

+0

@undefined不知道.html()也接受了一個函數,我將刪除我的答案,因爲我的答案中的.each()過於複雜。今天學到了新東西:D謝謝你! – thaJeztah 2013-02-08 23:39:31