Why won't this JS code work?
Can anyone tell me why when I use the following code, clicking on "Click Here" doesn't cause an alert? Is there any way to do this without adding an onClick a开发者_JAVA百科ttribute to the div tag?
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html>
<head>
<script type="text/javascript">
var clicker = document.getElementById("test");
clicker.onclick = test;
function test() {
alert('Test');
}
</script>
</head>
<body>
<div id="test">Click Here</div>
</body>
</html>
Because the element doesn't exist when you try to select it.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head></head>
<body>
<div id="test">Click Here</div>
<!-- moved the script to the end of the body element -->
<script type="text/javascript">
var clicker = document.getElementById("test");
clicker.onclick = test;
function test() {
alert('Test');
}
</script>
</body>
</html>
Looks like the JavaScript is running before the DOM loads. Try this:
window.onload = function(){
var clicker = document.getElementById("test");
clicker.onclick = test;
}
This JavaScript code gets executed before the document has loaded. This could be fixed by adding "onclick" as an attribute of the html tag (instead of dynamically registering it), or registering it in a function set as the "onload" attribute of the body tag. Also, on a somewhat separate note, why use that incredibly ancient doctype instead of the HTML5 doctype <!DOCTYPE html>?
The element 'test' has not been created when your JS is invoked. I suggest that you use jQuery and put your code inside it's document.Ready() method.
hold on the answers suggested here although they are pointing out the mistake correctly they are incorrect in some ways..
First of all you shouldnt have your Script tag within the body tag. It should always be in the head. you can jsut move the head tag to the end of the file.
Secondly as a web programmer you should always separate your concerns. Just an intro here: http://www.livestoryboard.com/Benefits/CMS-separation-of-concerns.html
Now with that in mind with respect to your program the concerns are the markup, css and script you should be having all your scripts in a separate js file and in the script tag you call document onload event and call the required function.
Hope all this makes sense
精彩评论