2013-03-24 63 views
0

我正在使用jQuery。我有一個像下面的一些代碼 -Jquery - 如何訪問被點擊的元素來運行一個函數?

---- ----- HTML

<table> 
<tr> 
<td class="cell" id="cell1" ></td> 
<td class="cell" id="cell2"></td> 
<td class="cell" id="cell3" ></td> 

</tr> 

<tr> 
<td class="cell" id="cell4"></td> 
<td class="cell" id="cell5"></td> 
<td class="cell" id="cell6"></td> 

</tr> 

</table> 

--- JS ----

$(".cell").click(function() { 

do_something(); 

} 

function do_something(){ 

// I want to print the id of the cell that was clicked here . 

} 

如何訪問導致函數運行的元素?比如,對於上面的代碼,我要訪問從功能do_Something()

+0

他要顯示的ID沒有價值,那麼試試這個:$(本).attr( 'ID') – tuffkid 2013-03-24 08:42:58

+2

'this.id'好得多... – 2013-03-24 08:43:18

回答

3
$(".cell").click(function() { 
    do_something(this); // this is the clicked element 
}); 
function do_something(element){ 
    console.log(element.id); // open the console to see the result 
} 

當然內被點擊的小區的ID它會更簡單,以簡單直接調用它:

$(".cell").click(do_something); 
function do_something(){ 
    console.log(this.id); // open the console to see the result 
} 

$(".cell").click(function(){ 
    console.log(this.id); // open the console to see the result 
}); 
+0

謝謝!我不能把函數放在裏面,因爲我需要在代碼中的許多地方這樣做 - 所以不必要的重複代碼。 – 2013-03-24 08:51:50

相關問題