zl程序教程

您现在的位置是:首页 >  前端

当前栏目

jQuery this事件

2023-06-13 09:12:02 时间
我们都知道,原生 JavaScript 中的 this 是非常复杂的。不过在 jQuery 中,this 的使用相对来说简单一点。jQuery 中的 this 大多数是用于事件操作中。

对于 jQuery 中的 this,我们记住一句话即可:this 始终指向触发当前事件的元素。

举例


 !DOCTYPE html 

 html 

 head 

 meta charset= utf-8 / 

 title /title 

 script src= js/jquery-1.12.4.min.js /script 

 script 

 $(function () {

 $( div ).click(function(){

 //$(this)等价于$( div )

 $(this).css( color , red 

 $( p ).click(function () {

 //$(this)等价于$( p )

 $(this).css( color , blue 

 /script 

 /head 

 body 

 div C语言中文网,给你初恋般的感觉~ /div 

 p C语言中文网,给你初恋般的感觉~ /p 

 /body 

 /html 

预览效果如图 1 所示。

this方法的效果
图 1:this 方法的效果

在$( div ).click(function(){ })中,$(this)等价于$( div )。而在$( p ).click(function(){ })中,$(this)等价于$( p )。

举例


 !DOCTYPE html 

 html 

 head 

 meta charset= utf-8 / 

 title /title 

 script src= js/jquery-1.12.4.min.js /script 

 script 

 $(function () {

 $( li ).each(function(index){

 var text = $( li ).text();

 console.log(text);

 /script 

 /head 

 body 

 li HTML /li 

 li CSS /li 

 li JavaScript /li 

 /ul 

 /body 

 /html 

预览效果如图 2 所示。

(this)效果
图 2:(this)效果

一开始想要实现的效果是依次输出每一个 li 元素中的文本,很多人自然而然就写下了上面这种代码。然后测试的时候,发现效果却是如图 3 所示的。这是怎么回事呢?

控制台信息
图 3:控制台信息

其实我们试着把$( li ).text()改为$(this).text()就有效果了。那么为什么用$( li )就不正确,而必须要用$(this)呢?原因在于$( li )获取的是一个集合,而不是某一个元素。

在事件函数中,如果想要使用当前元素,我们应尽量使用$(this)来代替$(selector)这种写法,否则可能会出现各种 bug。

23836.html

CSSC语言htmljavaJavaScript