<Script> if a problem occurs in the head or body, headbody
Today, I am going to look at the js advanced programming form chapter. When I look at the examples in the book, there is a problem. What's the problem? Let's just look at this code first?
<! DOCTYPE html> The code looks like this. In a simple form, there is a set of radio tags. The result is that the radio tags are obtained through the form, however, after I typed it out, the console always reported an error. The error message is as follows:
It means that the null elements attribute cannot be read. At first, I thought it was my code that was wrong, but after careful check, I found that it was correct, I even thought it was caused by the fact that the form did not write the action attribute, but I found that the same error was still reported after I tried it one by one, and I went to the example code in this book after I tried it, the sample code is as follows:
<! DOCTYPE html> After getting the sample code, I found that the operation was completed correctly and there were no errors. At that time, I was quite depressed. The two codes were almost identical. The only difference was that the <script> tag location was different, by convention, I wrote the <script> tag in the
<!DOCTYPE html>
Through the above code, I found that as long as the script code without the tag in the <body> operation is put there, it doesn't matter, but the loading sequence is different, just print 111 is the same as print 222. First print 111 in the head and then print 222 in the body. But when you need to operate the elements in the body, the script code in the head tag has a problem, that is, the elements to be operated cannot be found. After my experiment, I came to the conclusion that if the element in the body needs to be operated in the script, you must load the elements to be operated, that is, you must put the js Code of the operated element after the element.
Later, I checked the loading sequence of js and tags on the html page on the Internet, which is the same as my guess. html is loaded from top to bottom, when JavaScript or css is loaded using the connection method, a request is sent for loading. If the code is written directly, it is initialized directly. If it is a function, it is initialized directly, directly execute the function upon triggering. If the element in the body is operated on in the head, the function cannot be found because the element in the body is not loaded yet.
My understanding is like this for the moment. If something is wrong, you are welcome to correct it.