Advanced jQuery skills-DOM operations and jquery skills dom

Source: Internet
Author: User

Advanced jQuery skills-DOM operations and jquery skills dom
DOMReady event for page loading

The so-called domReady, that is, the document is ready. We all know that operations on dom must be performed only after the dom tree is loaded. How to detect that the DOM tree has been built is as follows:

1. Use jQuery:

// with jQuery$(document).ready(function(){ /* ... */ });// shorter jQuery version$(function(){ /* ... */ });

2. Listen to the DOMContentLoaded event, which is triggered after the DOM tree is created. Versions earlier than IE10 are not supported.

// without jQuery (doesn't work in older IEs)document.addEventListener('DOMContentLoaded', function(){// your code goes here}, false);

3. Monitors readyState status to implement cross-browser

Status attribute of readyState:

  • "Uninitialized"-Original Status
  • "Loading"-downloading data
  • "Loaded"-Download complete
  • "Interactive"-execution not completed
  • "Complete"-script execution completed
r(function(){  alert('DOM Ready!');});function r(f){/in/.test(document.readyState)?setTimeout('r('+f+')',9):f()}

This method constantly monitors the loading status of readyState. After loading is complete, the corresponding method is executed. Specific reference: http://www.dustindiaz.com/smallest-domready-ever

Code corresponding to the execution of a specific page

If the code on all pages is written in a JavaScript file, such code will be difficult to maintain. The simple method is to execute different code based on different pages. Let's take a look at the following example:

For example, test. js has the following code:

Var route = {_ routes: {}, // The routes will be stored here add: function (url, callback) {this. _ routes [url] = callback;}, run: function () {jQuery. each (this. _ routes, function (pattern) {// pattern points to the key of the _ routes object set, that is, url if (location. href. match (pattern) {// "this" points to the function to be executed this (); // this points to the value of the _ routes object set, that is, the method to be executed});} // Will execute only on this page: rout E.add('test.html ', function () {alert ('Hello there! '{}}}Route.add('products.html ', function () {alert ("this won't be executed :(") ;}); // You can even use regex-es: route. add ('. *. html ', function () {alert ('this is using a regex! ') ;}); Route. run ();
Use logic and operators

Logic and operators can be used to simplify the writing of conditional branch statements. For example:

General Syntax:

// Instead of writing this:if($('#elem').length){   // do something}

Better Syntax:

$('#elem').length && alert("doing something");
Very useful jquery is () method

The is () method is very useful. Here are some examples:

HTML:

<div id="elem"></div>

JS:

// Variable save jQuery object var elem =$ ('# elem'); // determines whether it is divelem. is ('div ') & console. log ("it's a div"); // whether the class name is included. bigboxelem. is ('. bigbox') & console. log ("it has the bigbox class! "); // Whether elem. is (': not (: visible)') & console. log (" it is den! "); // Set the element to execute the animation elem. animate ({'width': 200}, 1); // whether to execute the animation elem. is (': animated') & console. log ("it is animated! ");
Define an exists Function

To determine whether a jQuery object exists, you need to determine the length attribute. It can be encapsulated as an exists function to simplify the code and make it easier to read.

HTML:

<div id="elem"></div>

JS:

// General method console. log ($ ('# elem'). length = 1? "Exists! ":" Doesn' t exist! "); // Encapsulation method jQuery. fn. exists = function () {return this. length> 0;} console. log ($ ('# elem '). exists ()? "Exists! ":" Doesn' t exist! ");
Use the second parameter of the $ () function

The $ () function can receive two parameters. What is the role of the second parameter? Let's look at the example below:

<ul id="firstList" >      <li>one</li>      <li>two</li>      <li>three</li></ul><ul id="secondList" >      <li>blue</li>      <li>green</li></ul>

Role 1:

// Select an element. You can only select $ ('lil', '# firstlist') within the range of the current ul node by using # firstList '). each (function () {console. log ($ (this ). html ());});
// Equivalent to $ ('# firstlist'). find ('lil ');

Role 2:

// Create an element. The second parameter is the corresponding configuration property. If the jQuery method is included, var div =$ ('<div>', {"class": "bigBlue", "css ": {"background-color": "purple"}, "width": 20, "height": 20, "animate ": {// use the jQuery method as the property "width": 200, "height": 50}); div. appendTo ('body ');
Cancel the right-Click event
$(function(){    $(document).on("contextmenu" , function(e){             e. preventDefault();    });});
Unselect text
// Applicable to all browsers
$ ('P. descr '). attr ('unselectable', 'on '). css ('user-select', 'None '). on ('selectstart', false );
Parse anchor element URL
// URLvar url to be parsed = 'HTTP: // tutorialine.com/books/jquery-trickshots? Trick = 12 # comments '; // create a new link through url var a =$ (' <a> ', {href: url}); console. log ('host name: '+. prop ('hostname'); console. log ('path: '+. prop ('pathname'); console. log ('query: '+. prop ('search'); console. log ('Protocol: '+. prop ('protocol'); console. log ('hash: '+. prop ('hash '));

Output result:

Host name: tutorialine.com
Path:/books/jquery-trickshots
Query :? Trick = 12
Protocol: http:
Hash: # comments

The above is a summary of some knowledge. If you have any suggestions or questions, please leave a message for discussion.

Reference link:

Http://www.cnblogs.com/rubylouvre/p/4277408.html

Http://www.dustindiaz.com/smallest-domready-ever

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.