jQuery中event.target和this的区别详解

this和event.target的区别:

  1.js中事件是会冒泡的,所以this是可以变化的,但event.target不会变化,它永远指向触发事件的DOM元素本身;

  2.this和event.target都是dom对象,使用jQuey中的方法可以将他们转换为jquery对象:$(this)和$(event.target).

比如,一个很简单的例子.

$(event.target)指向触发事件的元素. 当点击蓝色小方框时, 蓝色小方框会变成橙色, 但其外围的大方框不会变色, 即没有触发事件的冒泡行为.

点击前:

jQuery中event.target和this的区别详解

点击后:

jQuery中event.target和this的区别详解

<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <style type="text/css"> *{ margin: 0; padding: 0; } #big { width: 200px; height: 200px; background-color: gray; } #small { width: 100px; height: 100px; background-color: blue; margin: 0 auto; } </style> </head> <body> <div> <div></div> </div> <script src="https://www.jb51.net/js/jquery-2.2.4.min.js" type="text/javascript" charset="utf-8"></script> <script type="text/javascript"> $("div, input").click(function (event) { $(event.target).css("background-color", "orange"); }); </script> </body> </html>

$(this)指向触发事件的元素. 当点击蓝色小方框时,蓝色小方框会变橙色, 同时其外围的灰色大方框也会变成橙色, 也就是说当用this获取触发事件的元素会引起事件的冒泡.

点击前:

jQuery中event.target和this的区别详解

点击后:

jQuery中event.target和this的区别详解

<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <style type="text/css"> *{ margin: 0; padding: 0; } #big { width: 200px; height: 200px; background-color: gray; } #small { width: 100px; height: 100px; background-color: blue; margin: 0 auto; } </style> </head> <body> <div> <div></div> </div> <script src="https://www.jb51.net/js/jquery-2.2.4.min.js" type="text/javascript" charset="utf-8"></script> <script type="text/javascript"> $("div, input").click(function () { $(this).css("background-color", "orange"); }) </script> </body> </html>

例二

onclick = changeImg(this)       vs     onclick = changeImg(event)

<img src='https://www.jb51.net/usa.gif' /> <script>   var myImages = [     'https://www.jb51.net/usa.gif','canada.gif','jamaica.gif','mexico.gif'   ];   function changeImg(e) {     var el = e.target;     var newImgNumber = Math.round(Math.round()*3);     while(el.src.indexOf(myImages[newImgNumber]) != -1){       el.src =myImages[newImgNumber];     }   } </script>

this是Javascript语言的一个关键字。

this代表函数运行时,自动生成的一个内部对象,只能在函数内部使用。

this和event.target的区别:

js中事件是会冒泡的,所以this是可以变化的,但event.target不会变化(在事件触发时,只传递当前event对象的引用),它永远是直接接受事件的目标DOM元素;

另外,this和event.target都是dom对象,如果要使用jquey中的方法可以将他们转换为jquery对象:$(this)和$(event.target);

到此这篇关于jQuery中event.target和this的区别详解的文章就介绍到这了,更多相关jQuery中event.target和this内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wxwfxs.html