gpt4 book ai didi

javascript - Jquery - 如何访问单击以运行函数的元素?

转载 作者:行者123 更新时间:2023-11-28 20:35:04 25 4
gpt4 key购买 nike

我正在使用 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
});

关于javascript - Jquery - 如何访问单击以运行函数的元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15596604/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com