gpt4 book ai didi

javascript - jquery "this"范围作为选择器

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

我正在编写一个用于学习目的的简单程序。它包含在日历上。每个标签都有一个 id。当我点击这个单元格时,我获得了 id

解决方法在这里:

$("td").click(function(){


alert($(this).attr("id"));

});

它工作正常。但是,在那之前,我试过这个:

$(this).click(function(){


alert($(this).attr("id"));

});

最后一个不起作用(返回未定义)。我想这与“这个”范围有关,但如果有人能解释我我将不胜感激,因为我不明白为什么第二个选项不起作用或这个范围是如何工作的。

最佳答案

这可能会有所帮助 jQuery Selectors .在你的代码中

$(this).click(function(){
alert($(this).attr("id"));
});

$(this)the current HTML element ,这意味着取决于代码的范围,$(this)是不同的 HTML 元素。在有效的代码中:

$("td").click(function(){
alert($(this).attr("id"));
});

代码范围在通过点击 <td></td> 触发的点击事件“内”元素,所以 $(this)指的是特定的 <td></td>并且只有它,同时执行点击事件中的代码。

希望对你有帮助。

关于javascript - jquery "this"范围作为选择器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49499792/

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