您的位置是:网站首页>Javascript编程Javascript编程

Javascript中事件对象的target和this的区别

少儿编程网2022-01-07 13:49:30Javascript编程 人已围观 来源:少儿编程 -用户投稿

简介1.当触发对象与绑定对象一致时<!DOCTYPEhtml><htmllang=en><head><metacharset=UTF-8><metahttp-equiv=X-UA-Compa

1.当触发对象与绑定对象一致时
m7f少儿编程网-https://www.pxcodes.com

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <ul class="list">
        <li class="itm">item1</li>
        <li class="itm">item2</li>
        <li class="itm">item3</li>
        <li class="itm">item4</li>
        <li class="itm">item5</li>
    </ul>
    <script>
        const li=document.querySelector("ul li:nth-of-type(4)");
        console.log(li);

        li.addEventListener("click",function(e){
            console.log(e.target);
            console.log(this);
        });
    </script>
</body>

</html>

点击item4这个li后,两者返回如下:
m7f少儿编程网-https://www.pxcodes.com

m7f少儿编程网-https://www.pxcodes.com

2.当触发对象与绑定对象不一致时m7f少儿编程网-https://www.pxcodes.com

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <ul class="list">
        <li class="itm">item1</li>
        <li class="itm">item2</li>
        <li class="itm">item3</li>
        <li class="itm">item4</li>
        <li class="itm">item5</li>
    </ul>
    <script>
        const ul=document.querySelector("ul");
        console.log(ul);
        ul.addEventListener("click",function(e){
            console.log(e.target);
            console.log(this);
        });
    </script>
</body>

</html>

点击item4这个li后,输出如下:
m7f少儿编程网-https://www.pxcodes.com

m7f少儿编程网-https://www.pxcodes.com

3.总结:m7f少儿编程网-https://www.pxcodes.com

  • target返回的是事件触发对象m7f少儿编程网-https://www.pxcodes.com

  • this 返回的是事件绑定对象
    m7f少儿编程网-https://www.pxcodes.com

推荐:《2021年js面试题及答案(大汇总)》

以上就是Javascript中事件对象的target和this的区别的详细内容,更多请关注少儿编程网其它相关文章!m7f少儿编程网-https://www.pxcodes.com

来源:php中文网m7f少儿编程网-https://www.pxcodes.com


相关文章:

支持一下 ( )

Javascript中事件对象的target和this的区别

      匿名评论
    • 评论
    人参与,条评论
    Javascript中事件对象的target和this的区别

微信公众号

免费视频教程

先知道