0

I am using jQuery . I have some code like below -

----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 . 

}

How do I access the element that caused the function to be run ? For eg in the above code , I want to access the id of the cell that was clicked from inside the function do_Something()

4

1 回答 1

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
}

当然,直接调用它会更简单:

$(".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
});
于 2013-03-24T08:44:02.280 回答