简体   繁体   English

addEventListener()不起作用-无法找出原因

[英]addEventListener() Not Working - can't figure out why

Wrote a super basic script to try out addEventListener and it's not working ... 写了一个超级基本的脚本来尝试addEventListener ,它不起作用...

Why? 为什么?

Here's the code: 这是代码:

<html>
    <head>
        <meta charset="utf-8" />
        <title></title>

        <script>

            function validateMe(){

                document.getElementById("button1").addEventListener("click",validateForm); 

                function validateForm(){
                    alert("Wheeeeee!");
                }

                window.addEventListener("load",validateMe);

            }

        </script>
    </head>
    <body>

        <form name="" id="" action="" onsubmit="return validateMe">
                First Name: <input type="input" name="first_name" id="first_name" />
                <br /><br />
                Last Name: <input type="input" name="last_name" id="last_name" />
                <br /><br />
                Email Address: <input type="input" name="email" id="email" />
                <br /><br />
                <input type="submit" value="Validate" id="button1" />
        </form>

    </body>
</html>

It seems you're trying to add the function from within the function itself. 似乎您正在尝试从函数本身内部添加函数。 The function will not get executed, therefore it will not be added. 该函数将不会执行,因此不会添加。 Try moving the addEventListener statement outside of the function block. 尝试将addEventListener语句移到功能块之外。 Or, make the function anonymous and declare it inside the addEventListener call. 或者,使函数匿名并在addEventListener调用中声明它。

Edit: I see now it does get executed on submit. 编辑:我现在看到它确实在提交时执行。 But the load phase has already passed so adding it at that point won't do anything. 但是加载阶段已经过去,因此在那时添加它不会执行任何操作。

Remove validateForm() . 删除validateForm() You have a function within the function which isn't being called anywhere. 您在函数内有一个未被任何地方调用的函数。

        function validateMe(){

            document.getElementById("button1").addEventListener("click",validateForm); 


                alert("Wheeeeee!");


            window.addEventListener("load",validateMe);

        }

Guessing from your case, You may want to use addEventListener() instead of in-line event usage. 根据您的情况进行猜测,您可能希望使用addEventListener()而不是addEventListener()事件用法。

You could remove in-line event onsubmit="return validateMe" from the form DOM, then your window.addEventListener("load",validateMe) needs to be called out of its function: 您可以从DOM形式中删除onsubmit="return validateMe"事件onsubmit="return validateMe" ,然后需要从其函数中调用window.addEventListener("load",validateMe)

function validateMe(){  
  document.getElementById("button1").addEventListener("click",validateForm); 
  function validateForm(){
    alert("Wheeeeee!");
  }
}
window.addEventListener("load", validateMe);

JSfiddle Demo JSfiddle演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM