jquery Advanced Techniques--dom Operation Chapter

Source: Internet
Author: User

Page Load Domready Event

The so-called Domready, which is document readiness, we all know that the DOM tree must be loaded before it can be manipulated. How to detect that the DOM tree has been built, here are some ways to do it:

1. Use jquery:

// with JQuery$ (document). Ready (function/** / }); // shorter jQuery version$ (function/** /});

2. Listen for domcontentloaded events, the DOM tree is created and will be triggered, and the following versions of IE10 are not supported.

// without jQuery (doesn ' t work in older IEs) function () {//  Your code goesherefalse);

3. Monitor the readystate status to enable cross-browser

ReadyState State Properties:

    • "Uninitialized" – Original state
    • "Loading" – in the download data
    • "Loaded" – Download complete
    • "Interactive" – not done yet
    • "Complete" – Script execution completed
R (function() {  alert (' DOM ready! ') );}); function R (f) {/in/.test (document.readystate)? SetTimeout (' R (' +f+ ') ', 9): F ()}

This method is constantly listening to the loading state of the readystate, and then executes the corresponding method when the load is complete. For specific reference: Http://www.dustindiaz.com/smallest-domready-ever

Code that corresponds to the execution of a particular page

If all of the page's code is written in a JavaScript file, this code is difficult to maintain. The easy way is to execute different code depending on the page. Take a look at the example:

For example, the test.js has the following code:

varRoute ={_routes: {},//The routes is being stored hereAddfunction(URL, callback) { This. _routes[url] =callback; }, run:function() {Jquery.each ( This. _routes,function(pattern) {//the pattern points to the key of the _routes object collection, which is the URL                if(Location.href.match (pattern)) {//' This ' points to the function to be executed                     This();//This points to value that points to the collection of _routes objects, which is the method to be executed                }            }); }    }    //Would execute only on the This page:Route.add (' test.html ',function() {alert (' Hello there! ');}); Route.add (' Products.html ',function() {alert ("This won ' t is executed:(");});//can even use regex-es:Route.add ('. *.html ',function() {alert (' This is using a regex! ');}); Route.run ();
Using Logic and operators

Using logic and operators, you can simplify the wording of conditional branching statements, for example:

The general wording:

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

Better notation:

$ (' #elem '). Length && alert ("doing something");
A very useful jquery is () method

The IS () method is useful to take a look at some examples:

Html:

<id= "Elem"></div>

Js:

Variable save jquery object var elem = $ (' #elem '); // determine if divelem.is (' div ') && console.log ("It ' s a div"); // whether to include the class name. BigBoxelem.is ('. BigBox ') && console.log ("It has the BigBox class!" ); // visible elem.is (': Not (: visible) ') && Console.log ("It is hidden!" ); // set element execution animation elem.animate ({' width ': 200},1); // whether to perform animation elem.is (': Animated ') && Console.log ("It is animated!");
Define a exists function

Determining if a jquery object exists needs to be judged by the length property, which can be encapsulated as a exists function, simplifying the code and making it easier to read.

Html:

<id= "Elem"></div>

Js:

// General Method Console.log ($ (' #elem '). length = = 1? "exists!": "Doesn ' t exist!" ); // Encapsulation Method function return this. length > 0;} Console.log ($ (' #elem '). Exists ()? "exists!": "Doesn ' t exist!");
Use the second argument of the $ () function

The $ () function can receive two parameters, what the second parameter does, and can look at an example:

<ulID= "Firstlist" >      <Li>One</Li>      <Li>Both</Li>      <Li>Three</Li></ul><ulID= "Secondlist" >      <Li>Blue</Li>      <Li>Green</Li></ul>

Function One:

// Select an element through the #firstlist limit element to select $ (' li ', ' #firstList ') only within the current UL node range. Each (function() {    Console.log ($ (this). html ());});
Equivalent to $ (' #firstList '). Find (' Li ');

Function Two:

// creates a single element. The second parameter is the corresponding configuration property, including the JQuery method, which will be executed by the var div =$ (' <div> ' "Class": "Bigblue" "CSS"  "Background-color": "Purple""width":"height"://  Use the JQuery method as the property "width":"height": ());d iv. appendTo (' body ');
Cancel Right Click event
$ (function() {    $ (document). On (function(e) {             E. preventdefault ();    });});
Cancel Text selection
Adapt to all browsers
$ (' P.DESCR '). attr (' unselectable ', ' on ' ) . css (' user-select ', ' None ' ) . On (false);
Parse anchor element URL
// URLs that need to be resolved var url = ' http://tutorialzine.com/books/jquery-trickshots?trick=12#comments ' ; // Create a new link from a URL var a = $ (' <a> ' , {href:  URL}); console. log (' Host name: ' + A. Prop (' hostname ' )); console . Log (' Path: ' + A. Prop (' pathname ' )); console. Log (' Query: ' + A. Prop (' search ') ); Log (' Protocol: ' + A. Prop (' Protocol ' )); Log (' hash: ' + A. Prop (' hash '));

Output Result:

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

Above is some knowledge summary, if have any suggestion or the question, welcome the message discussion.

Reference Links:

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

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

jquery Advanced Techniques--dom Operation Chapter

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.