Today, I saw a test case of w3school JS click event http://www.w3school.com.cn/tiy/t.asp?f=js_ dom_ event_ Onclick4, its code is:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<p>The <em>displayDate()</em> function can be executed by clicking the button. </p>
<button id="myBtn"> click here</button>
<script>
document.getElementById("myBtn").onclick=function(){displayDate()};
function displayDate()
{
document.getElementById("demo").innerHTML=Date();
}
</script>
<p id="demo"></p>
</body>
</html>
The click effect is normal. When I test code, I usually write JS code in the head tag. If the JS code is moved to the head tag, the browser will report an error and prompt: uncaught type error: cannot set property ‘onclick’ of null
After analyzing the code, w3school is written as JS after the browser loads the button node, so I changed the code to:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script>
window.onload=function(){
document.getElementById("myBtn").onclick=function(){displayDate()};
function displayDate(){
document.getElementById("demo").innerHTML=Date();
}
}
</script>
</head>
<body>
<p>The <em>displayDate()</em> function can be executed by clicking on the button. </p> <button id="myBtn"> click here</button>
<p id="demo"></p>
</body>
</html>
The test passed, indicating that the node needs to be loaded before the onclick event can be executed
Similar Posts:
- [How to Solve] Cannot set property ‘onclick’ of null
- JavaScript Uncaught TypeError: Cannot set property ‘innerHTML’ of null”
- ”Cannot read property ‘addEventListener’ of null“
- Interaction between web browser and JavaScript in WPF
- Js Error: SyntaxError: identifier starts immediately after numeric literal
- Document.body.clientheight cannot get the browser page height correctly
- window.location And window.open The difference between
- Always report uncaught error:[$ injector:modulerr ]Solutions to errors
- How to deal with the error “cannot read property ‘set state’ of undefined” in react
- Solve the problem of style in cannot read property ‘style’ of null