Perfect jquery processing mechanism

  • 2021-01-02 21:44:51
  • OfStack

Using the jQuery selector is not only much cleaner than using the traditional getElementById() and getElementsByTagName() functions, but it also avoids some errors. Here are some examples:


 <script>
  document.getElementById("div").style.color ="red";
 </script>

After running the above code, the browser reports an error because there are no ID div elements in the page.

The improved code is as follows:


<script>
   if(document.getElementById("div")){ // With the IF Statement to determine if there is ID for div If any, execute the following code  
    document.getElementById("div").style.color ="red"
   }
</script>

This prevents the viewer from reporting errors, but if you have a lot of elements to work with, you might have to make a judgment on each one once, and the jquery handling is pretty good, even if you use JQUERY to get elements that don't exist in the web page.

The code is as follows:


 <script>
  $("#div").css("color","red");
 </script>

With this precaution, you don't have to worry about the page's JavaScript error if you later delete a previously used element from the page for some reason.

Note:

$("div") will always fetch the jquery object, even if the element is not on the web page. So when jquery is used to check for the presence of an element on a web page.

The following code cannot be used:


<script>
 if($("#div")){
   $("#div").css("color",red) // The browser will report an error 
  }
</script>

It should be judged by the length of the fetch.

The code is as follows:


<script>
 if($("#div").length >0){
   $("#div").css("color",red)
 }
</script>

This can also be converted to an DOM object to determine.

The code is as follows:


<body>
  <div id="div">ccccccc</div>
<script src="jquery-2.1.4.min.js"></script>
<script>
  var $div = $("#div");
  var div = $div[0];
  if(div){
    $div.css("color","red")  // At this time DIV The color of theta is going to be theta red
  }
</script>
</body>

This is the jquery perfect processing mechanism, I hope to help you learn jquery programming.


Related articles: