EventListeners没有触发(即使在最后包含JavaScript之后)

时间:2013-07-26 20:28:41

标签: javascript getelementbyid

这不是"Why does jQuery or a DOM method such as getElementById not find the element?".的副本我有一个应该触发一堆事件的表单,但没有一个函数被调用。我添加了一个按钮,仅用于测试。

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset ="utf-8" />
    <title>Sign in</title>
    <link rel="stylesheet" type="text/css" href="main.css" />
    <link rel="stylesheet" type="text/css" href="passphrase.css" />
</head>
<body>
    <noscript>
        Javascript is disabled. Now redirecting.
    <meta HTTP-EQUIV="REFRESH" content="0; url=passnojs.html"> 
    </noscript>
    Welcome.
    <form method="post" action="prolevel2.php" id="loginForm">
        <!--code snipped-->
        <br /><br /><input type="button" value="big ugly button" id="testing" />
    </form>
    <script src="verify.js"></script><!--this should work because it's after the HTML-->
</body>
</html>

包含外部JavaScript

alert("begining")
document.getElementById('testing').addEventListener('onclick', display, false)
alert("here now")
function display()
{
    alert("now displaying")//doesn't work
}

“开始”和“此处现在”显示,但“现在显示不是”。控制台中没有消息。我做错了什么?

2 个答案:

答案 0 :(得分:2)

试试这个

document.getElementById('testing').addEventListener('click', function(){alert("now displaying")}, false);

document.getElementById('testing').addEventListener('click',display, false);

答案 1 :(得分:0)

您有语法错误,正如其他人提到的那样。 “onclick”应该是“点击”。对于默认事件,我更喜欢使用属性而不是addEventListener,如果输入错误,会抛出正确的语法错误:

alert("begining")
document.getElementById('testing').onclick = display;
alert("here now")
function display()
{
    alert("now displaying");//doesn't work
}

http://jsfiddle.net/MaxPRafferty/N4qGB/