A classmate who had just written the front end yesterday sent a message asking this question (e.g.):
The HTML code is (omit part of the code):
1 <Head>2 <Scriptsrc= "Test.js"></Script>3 </Head>4 <Body>5 <DivID= "Output">0</Div>6 <ButtonID= "Plus">+1</Button>7 <ButtonID= "Minus">-1</Button> 8 </Body>
The Test.js initial code is:
1 var plus= document.getElementById (' Plus ' 2 3 4 plus.addeventlistener (' click ', function () { 5 console.log (' +1 ' ); 6 },false );
As a result, the error of "uncaught typeerror:cannot Read Property ' AddEventListener ' of NULL" was reported for the console because the HTML DOM structure was not loaded when it was completed. The JS file has been loaded and the DOM element is bound to an event operation, so null errors cannot be reported, and sometimes undefined errors may occur.
The way to solve this problem can be considered in the following two ways:
First, put <script> in the HTML file at the end of the DOM load, namely:
1 <Body>2 <DivID= "Output">0</Div>3 <ButtonID= "Plus">+1</Button>4 <ButtonID= "Minus">-1</Button>5 <Scriptsrc= "Test.js"></Script> 6 </Body>
Second, in the JS code block put into the Window.onload event, the basic document structure to be loaded after the completion of the event binding:
1Window.onload =function() {2 varplus = document.getElementById (' Plus ');3 varminus = document.getElementById (' minus '));4 varOutput = document.getElementById (' Output ');5Plus.addeventlistener (' click ',function() {6Console.log (' +1 ');7},false);8}
Of course, this can also be done with jquery's ready function, similar in principle. PS: The interview in the previous days encountered such a problem: to say that the domcontentloaded event, the onload event and JQ's ready event, in fact, there is a difference, a blog post on this issue, the first to leave a hole.
Then the problem is solved, the following is the completion of the function, required to press the "+1" button, the number +1; Press "1" button, the number-1;
Of course, the problem is relatively easy to understand the scope and closure can be written out, but also for the students to do out. The HTML code is the same as above, the following is the complete JavaScript code:
1Window.onload =function() {2 varplus = document.getElementById (' Plus ');3 varminus = document.getElementById (' minus '));4 varOutput = document.getElementById (' Output ');5 varnum=Output.innertext;6 varCount =function(event) {7 vartarget=Event.target;8 Switch(target.id) {9 Case' Plus ':Tennum++; Oneoutput.innertext=num; A Break; - - Case' Minus ': thenum--; -output.innertext=num; - Break; - } + }; -Document.addeventlistener (' Click ', Count,false); +}
The final results are as follows:
The reason of JavaScript method Undefined/null and the simple implementation of closure package