美文网首页Web前端之路我爱编程程序员
javascript中关于事件句柄EventListener的疑

javascript中关于事件句柄EventListener的疑

作者: 祝我好运zz | 来源:发表于2018-04-16 20:24 被阅读14次

javascript中关于事件句柄EventListener的疑问记录

<!DOCTYPE html>  
<html lang="en">  
<head>  
    <meta charset="UTF-8">  
    <title>Document</title>  
</head>  
<body>  
    <p id="pid">Hello</p>  
    <button id="btn">按钮</button>  
    <script>  
        var x=document.getElementById("btn");  
        x.addEventListener("click",hello);//句柄  
        x.addEventListener("click",world);  
        x.removeEventListener("click",hello);  
        function hello(){  
            alert("Hello");  
        }  
        function world(){  
            alert("world");  
        }  
    </script>  
</body>  
</html>  

情况1:

x.addEventListener("click",hello);//句柄  
x.addEventListener("click",world);  
//x.removeEventListener("click",hello);  

在视频教学中,说此处的函数调用不用加(),此时运行的结果是:



点击按钮,会弹出消息框“hello",点击确定后,会再弹出对话框"world"。

情况2:

x.addEventListener("click",hello());//句柄  
x.addEventListener("click",world());  
//x.removeEventListener("click",hello);  

添加()后,此时运行结果是:点击按钮没有反应,然后点击刷新,会先弹出消息框“hello",点击确定后,会再弹出对话框"world"。

情况3:

x.addEventListener("click",hello);//句柄  
x.addEventListener("click",world());  
//x.removeEventListener("click",hello); 
x.addEventListener("click",hello());//句柄  
x.addEventListener("click",world);  
//x.removeEventListener("click",hello);  

如果任意一个加(),一个不加(),那么点击按钮会弹出不加()的那个对应的消息框,点击刷新会出现加()括号的那个对应的消息框。

情况4:

x.addEventListener("click",hello);//句柄  
//x.addEventListener("click",world);  
x.removeEventListener("click",hello);  

在视频教学中不加(),按按钮没有任何反应,事件句柄被删除。

情况5:

x.addEventListener("click",hello());//句柄  
//x.addEventListener("click",world);  
x.removeEventListener("click",hello());  

两个都加(),按钮没有反应,刷新出现两次"hello"对话框。

情况6:

x.addEventListener("click",hello);//句柄  
//x.addEventListener("click",world);  
x.removeEventListener("click",hello()); 
x.addEventListener("click",hello());//句柄  
//x.addEventListener("click",world);  
x.removeEventListener("click",hello); 

如果其中一个不加,那么结果如下:
当第一个不加时,点击按钮和刷新各会弹出一个消息框;当第二个不加时,按钮没反应,刷新出现一个消息框。

分了六种情况,搞得自己都晕头晕脑的,暂时还未明白其中道理,等我了解清楚后,再来此处解答!


小哥哥我终于搞明白了!!!

JS中函数名后面的括号加与不加的区别

首先我们要明白一个概念:JavaScript 的函数是一等公民,可以作为参数传入别的函数,也可以作为一个函数的返回值,也可以被重新赋值。也就是说和变量一样。
举个例子:

function test(str) {  
        str+=1;  
       return str;  
    }  
    var demo1=test(1);  
    console.log(demo1);//2 返回的是执行函数得到的值  
  
    var demo2=test;  
    console.log(demo2);//function test() 返回的是函数体本身  

不加括号的时候,是表示这个函数本体,也是函数的指针,当加括号的时候,就等于引用该函数,直接得到该函数的返回值。
所以对于我们这里的情况,就很好解释了, addEventListener (参数1,参数2);function函数在这里是作为参数导入,应该用函数体,所以不加括号,所以没加括号的时候按钮正常运行;如果加了括号等于这里导入的参数是function函数的返回值,那么调用的结果就是undefined。
所以当我们点击刷新时,加括号的函数就直接被执行(ps:js中可以执行一个语句中的一部分)。
更详细的解释,请看:https://www.zhihu.com/question/31044040(我也是从知乎大神处看的,嘻嘻)。

相关文章

网友评论

    本文标题:javascript中关于事件句柄EventListener的疑

    本文链接:https://www.haomeiwen.com/subject/etxykftx.html