[英]JavaScript event not being fired
Once #theButton
is clicked, an alert should be triggered.单击#theButton
,应触发警报。 Why aren't any of the events being triggered using the following methods?为什么使用以下方法没有触发任何事件?
var theButton = document.getElementById("theButton");
theButton.onclick = function(){alert("Clicked!");}
theButton.onclick = clickAlert;
theButton.onclick(alert("Clicked!"));
function clickAlert(){
alert("Clicked!");
}
</script>
</head>
<body>
<input type="button" id="theButton">
</body>
</html>
You have three problems你有三个问题
function
on line 7. (This generates a runtime error, by the way)您在第 7 行拼错了function
。(顺便说一下,这会产生运行时错误)onclick
property on line 8 - not sure if you're doing that on purpose or what您覆盖了第 8 行的onclick
属性 - 不确定您是故意这样做还是什么Because theButton
doesn't exist yet when you run your script?因为当您运行脚本时theButton
还不存在?
Wrap it into the body's onload
event or jQuery's ready()
.将它包装到主体的onload
事件或 jQuery 的ready()
。
尝试将其包装在 document.Ready() 函数中。
我喜欢jQuery.ready()
答案,但我相信您也可以将<script>
块移动到某个点,就像在页面末尾一样取消按钮。
It works if you put the onclick within the input tag (and spell things right):如果您将 onclick 放在输入标签中(并且拼写正确),它会起作用:
<html>
<head>
<script type="text/javascript" language="javascript">
function clickAlert(){
alert("Clicked!");
}
</script>
</head>
<body>
<input type="button" id="theButton" NAME="theButton" onclick="clickAlert()">
</body>
</html>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.