<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script>
//Get this element from the document based on the value of the id attribute
var btnObj=document.getElementById("btn");
// for the current button element (object), register the click event, add the event handler (anonymous function)
btnObj.onclick=function(){
//response to do something
alert("jaja");
};
</script>
</head>
<body>
<input type="button" value="Display effect" id="btn" />
</body>
</html>
After the above code is executed, the
To make changes, you need to put the JS file at the bottom of and load it
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<input type="button" value="show effect" id="btn" />
<script>
//get this element from the document based on the value of the id attribute
var btnObj=document.getElementById("btn");
// for the current button element (object), register the click event, add the event handler (anonymous function)
btnObj.onclick=function(){
//response to do something
alert("jaja");
};
</script>
</body>
</html>
The code executes normally
Reason: when the JS file is placed in the head, if the onclick or OnMouseOver event is bound, a similar error will appear as shown in the figure above. The reason is that the order of loading the HTML document you write is from top to bottom, and the JS is executed only after the button node is loaded. Therefore, when the browser parses from top to bottom, the button node bound to onclick cannot be found, so an error is reported
The solution: first, load the JS file at the bottom; Second, use window. Onload = function () {} to wrap JS content
Similar Posts:
- How to Solve Error: Cannot set property ‘onclick’ of null
- JavaScript Uncaught TypeError: Cannot set property ‘innerHTML’ of null”
- ”Cannot read property ‘addEventListener’ of null“
- Document.body.clientheight cannot get the browser page height correctly
- Always report uncaught error:[$ injector:modulerr ]Solutions to errors
- Error in JS function referencing public page [How to Solve]
- window.location And window.open The difference between
- The Difference between $(document).ready, window.onload and $(window).load(function (){})
- XMLHttpRequest status=0 (All You Should Know)
- Js Error: SyntaxError: identifier starts immediately after numeric literal