Home > Web Front-end > JS Tutorial > body text

Perfect jquery processing mechanism_jquery

WBOY
Release: 2016-05-16 15:14:37
Original
973 people have browsed it

Using jQuery selectors is not only much simpler than using the traditional getElementById() and getElementsByTagName() functions, but it can also avoid certain errors. Please see the example below:

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

After running the above code, the browser will report an error because there is no element with the ID of div in the web page.

The improved code is as follows:

<script>
   if(document.getElementById("div")){ //用了IF语句来判断是否有ID为div的元素,如果有,执行下面代码 
    document.getElementById("div").style.color ="red"
   }
</script>
Copy after login

This can avoid browser errors, but if there are many elements to be operated, each element may have to be judged once, and jquery handles the problem very well, even if JQUERY is used to obtain the web page that does not exist Elements will not report an error.

The code is as follows:

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

With this preventive measure, even if a previously used element on the webpage is deleted for some reason in the future, there is no need to worry that the JavaScript of this webpage will report an error.

Note:

$("div") always obtains a jquery object, even if there is no such element on the web page. So when you want to use jquery to check whether an element exists on the web page.

The following code cannot be used:

<script>
 if($("#div")){
   $("#div").css("color",red) //这样游览器会报错
  }
</script>
Copy after login

It should be judged based on the obtained length.

The code is as follows:

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

At this time, it can also be converted into a DOM object for judgment.

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")  //此时DIV的颜色就变为red
  }
</script>
</body>
Copy after login

This is the perfect processing mechanism of jquery. I hope it will be helpful for everyone to learn jquery programming.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!