繁体   English   中英

jQuery-如何访问被单击以运行功能的元素?

[英]Jquery - How do I access the element that was clicked to run a function?

我正在使用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。

$(".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
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM