Jquery's complete processing mechanism and jquery's complete mechanism
Using the jQuery selector is much simpler than using the traditional getElementById () and getElementsByTagName () functions, and can avoid certain errors. See the following example:
1 <script>2 document.getElementById("div").style.color ="red";3 </script>
After running the code above, the browser reports an error because the webpage does not have an element with the ID as div.
The improved code is as follows:
1 <script> 2 if (document. getElementById ("div") {// use the IF statement to determine whether there is an element whose ID is div. IF yes, run the following code 3 document. getElementById ("div "). style. color = "red" 4} 5 </script>
In this way, you can avoid errors reported by the browser. However, if there are many elements to be operated on, you may have to make a judgment on each element. The jquery processing is very good, that is, using JQUERY to retrieve elements that do not exist in a webpage does not return an error.
The Code is as follows:
1 <script>2 $("#div").css("color","red");3 </script>
With this precaution, even if you delete a previously used element on a webpage for some reason in the future, you don't have to worry about the JavaScript error of this webpage.
Note:
$ ("Div") is always a jquery object, even if this element is not found on the webpage. Therefore, when jquery is used to check whether an element exists on a webpage.
You cannot use the following code:
1 <script> 2 if ($ ("# div") {3 $ ("# div" ).css ("color", red) // The browser reports an error of 4} 5. </script>
It should be determined by obtaining the length.
The Code is as follows:
<script> if($("#div").length >0){ $("#div").css("color",red) }</script>
At this time, it can also be converted to a DOM object for judgment.
The Code is as follows:
1 <body> 2 <div id = "div"> ccccccc </div> 3 <script src = "jquery-2.1.4.min.js"> </script> 4 <script> 5 var $ div = $ ("# div "); 6 var div = $ div [0]; 7 if (div) {8 $div.css ("color", "red ") // The Color of the DIV changes to red 9} 10 </script> 11 </body>