当前位置:网站首页>15 Uncaught TypeError: Cannot set properties of null (setting ‘onclick‘)

15 Uncaught TypeError: Cannot set properties of null (setting ‘onclick‘)

2022-06-09 13:56:00 I want to walk the whole stack

1、 Error code

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title> title </title>
    <style type="text/css"> </style>

        <script type="text/javascript"> // obtain button object  var btn = document.getElementById("btn"); // Bind a handler to the corresponding event of the button to respond to the event , When the event is triggered , The corresponding function will be called  btn.onclick = function () {
       alert(" Triggered a click event "); }; var btn1 = document.getElementById("btn1"); var btn2 = document.getElementById("btn2"); btn1.onclick = function () {
       document.getElementById("t2").value = document.getElementById("t1").value }; btn2.onclick = function () {
       document.getElementById("t2").value = "" } </script>

</head>

<body>
    <button id="btn"> I'm the button </button>

    <br><br>
    <input id="t1" type="text" value=" Text 1">
    <input id="t2" type="text">
    <button id="btn1">copy</button>
    <button id="btn2"> Cancel </button>


</body>

</html>

2: Reasons for reporting errors

The loading process of the document is from top to bottom . Use unnamed variables 、 Will report a mistake

3、 terms of settlement

1、 take Javascript Code from <head> Put... In the label <body> in
2、 If you have to put this code into head What to do in the label ???

 Insert picture description here
The modified code

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title> title </title>
    <style type="text/css"> </style>

        <script type="text/javascript"> window.onload = function(){
       // obtain button object  var btn = document.getElementById("btn"); // Bind a handler to the corresponding event of the button to respond to the event , When the event is triggered , The corresponding function will be called  btn.onclick = function () {
       alert(" Triggered a click event "); }; var btn1 = document.getElementById("btn1"); var btn2 = document.getElementById("btn2"); btn1.onclick = function () {
       document.getElementById("t2").value = document.getElementById("t1").value }; btn2.onclick = function () {
       document.getElementById("t2").value = "" } } </script>

</head>

<body>
    <button id="btn"> I'm the button </button>

    <br><br>
    <input id="t1" type="text" value=" Text 1">
    <input id="t2" type="text">
    <button id="btn1">copy</button>
    <button id="btn2"> Cancel </button>


</body>

</html>
原网站

版权声明
本文为[I want to walk the whole stack]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/160/202206091237180047.html