JavaScript event not being fired
Once #theButton
is clicked, an alert should be triggered. 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(&开发者_Python百科quot;Clicked!"));
function clickAlert(){
alert("Clicked!");
}
</script>
</head>
<body>
<input type="button" id="theButton">
</body>
</html>
You have three problems
- You misspell
function
on line 7. (This generates a runtime error, by the way) - You try to access the node #theButton before it's available in the DOM. Take Pekka's advice for this one
- You overwrite the
onclick
property on line 8 - not sure if you're doing that on purpose or what
Because theButton
doesn't exist yet when you run your script?
Wrap it into the body's onload
event or jQuery's ready()
.
Try wrapping it in the document.Ready() function.
I like the jQuery.ready()
answer, but I believe you could also move the <script>
block to some point afeter you delcalre the button like at the end of the page.
It works if you put the onclick within the input tag (and spell things right):
<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>
精彩评论