我正在使用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()
中单击的单元格的id。答案 0 :(得分: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
});