2013-03-24 62 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

相关问题