page Load Domready event
The so-called Domready, the document is ready, we all know that in the operation of the DOM must be done after the DOM tree is finished loading. How to detect that the DOM tree has been built, here are some ways to implement it:
1. Use jquery:
With JQuery
$ (document). Ready (function () {/* ... */});
Shorter jQuery version
$ (function () {/* ... */});
2. Listening for domcontentloaded events, the DOM tree is created and is triggered, and IE10 the following version is not supported.
Without jQuery (doesn ' t work in older IEs)
Document.addeventlistener (' domcontentloaded ', function () {
Your code goes here
}, False);
3. Monitor readystate State, can realize cross-browser
ReadyState Status Properties:
"Uninitialized"? Original state
"Loading"? In the download data
"Loaded"? Download complete
"Interactive"? Not finished yet
"Complete"? Script Execution Complete
R (function () {
Alert (' DOM ready! ');
});
function r (f) {/in/.test (document.readystate)? SetTimeout (' R (' +f+ ') ', 9): F ()}
This method is to continuously monitor the loading state of the readystate, and then execute the corresponding method after the loading is complete. Specific can refer to: 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, such code will be difficult to maintain. The easy way to do this is to execute different code based on different pages. Take a look at the example:
For example, the following code is available in Test.js:
var route = { _routes: {}, // the routes will be stored here add: function (url, callback) {
this._routes[url] = callback;        &NBSP}, run: function () { jquery.each (this._ Routes, function (pattern) { // pattern key that points to the collection of _routes objects, that is, url if (Location.href.match (pattern)) { // "This" points to the function tO be executed this (); //this points to value that points to a collection of _routes objects, that is, the method to execute }
}); } } // will execute only on this page:route.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 ();
Using Logical AND Operator
The use of logic and operators can simplify conditional branching statements, examples:
The general wording:
Instead of writing this:
if ($ (' #elem '). Length) {
//do something
}
Better way to do it:
$ (' #elem '). Length && alert ("doing something");
Very useful jquery is () method
The IS () method is useful to look at some examples:
Html:
<div id= "Elem" ></div>
Js:
Variable save jquery object
var elem = $ (' #elem ');
Judge whether Div
elem.is (' div ') && console.log ("It ' s a div");
Contains the class name. BigBox
elem.is ('. BigBox ') && console.log ("It has BigBox");
Visible
elem.is (': Not (: visible) ') && Console.log ("It is hidden!");
Sets the element to perform an animated
elem.animate ({' width ': 200},1);
Whether to perform animation
elem.is (': Animated ') && Console.log ("It is animated!");
Define a exists function
Determining whether a jquery object exists needs to judge the length attribute, which can be encapsulated as a exists function, simplifying the code and making 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 argument of the $ () function
The $ () function can receive two parameters and what the second parameter does, you can take a look at the following example:
<ul id= "Firstlist" >
<li>one</li>
<li>two</li>
<li>three </li>
</ul>
<ul id= "secondlist" >
<li>blue</li>
<li>gree N</li>
</ul>
Function One:
Select an element by #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 an element. The second parameter is the corresponding configuration property, and the JQuery method is executed with the
var div = $ (' <div> ', {
"class": "Bigblue",
"CSS": {
"background-c Olor ":" Purple "
},
" width ":"
height ":"
animate ": {///using jquery method as attribute
" width ": 200 ,
"height":}
);
Div. appendto (' body ');
Cancel Right Click event
$ (function () {
$ (document). On ("ContextMenu", function (e) {
E. preventdefault ();
});
});
Cancel Text selection
Adapts to all browsers
$ (' p.descr '). attr (' unselectable ', ' on ')
. css (' user-select ', ' none ')
. On (' Selectstart ', false);
Resolve anchor Element URL
// URL to parse var url = ' http://tutorialzine.com/books/
Jquery-trickshots?trick=12#comments ' ;
Create a new link through the 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 ' );
Console. log (' protocol: ' + a. prop (' Protocol ' )); Console. log (' hash: ' + a. prop (' Hash ' );
Output:
Host name:tutorialzine.com
Path:/books/jquery-trickshots
Query:? trick=12
Protocol:http:
Hash: #comments
decrypt jquery kernel dom operation
jquery's approach to inserting DOM operations has about 10 kinds of
Append, prepend, before, after, ReplaceWith
Appendto, Prependto, InsertBefore, InsertAfter, ReplaceAll
are divided into 2 groups, up and down control, to achieve the same function. The main differences are the syntax-especially the location of the content and the target
The Dommanip,buildfragment module that it relies on has previously analyzed
to insert the content specified by the parameter after each element in the matching element collection as its sibling node
for. After (), select the expression before the function, and the argument is what you want to insert.
for. InsertAfter (), on the contrary, the content is preceded by the method, and it is placed behind the element in the argument.
after
After:function () {return
this.dommanip (arguments, function (elem) {
if (This.parentnode)
{ This.parentNode.insertBefore (Elem, this.nextsibling);
}
});
},
It's been mentioned before. All methods rely on This.dommanip merge parameter processing, internally through the Buildfragment module to build document fragments
The specific execution of each method is then provided through a callback to handle
The DOM operation does not provide a way to insert a sibling node directly after the current node, but provides a similar method
InsertBefore () Method: You can insert a new child node before an existing child node. Syntax: InsertBefore (Newchild,refchild)
See how jquery handles it.
For example
Inner.after (' <p>Test</p> ');
The inside will build the ' <p>Test</p> ' through buildfragment the document Elem
Then through This.parentNode.insertBefore (Elem, this.nextsibling);
This here is the corresponding inner, Elem is ' <p>Test</p> '
See here is very good understanding of after the implementation of
Simple simulation with native method
var inner = document.getelementsbyclassname (' inner ') for
(var i =0; i<inner.length;i++) {
var elem = inner[ I]
var div = document.createelement (' div ')
div.innerhtml = ' aaaa '
elem.parentNode.insertBefore (div , elem.nextsibling)
}
InsertAfter
The designers of the jquery code are smart enough to incorporate similar functionality as much as possible, and the code is more refined and aesthetically pleasing.
Jquery.each ({
appendto: "Append",
prependto: "prepend",
insertbefore: "Before",
Insertafte R: "After",
ReplaceAll: "replacewith"
}, function (name, original) {
jquery.fn[name] = function (SE lector) {
};
});
DEMO
$ (' <p>Test</p> '). InsertAfter ('. inner ');
A document is built through $ (' <p>Test</p> '), and the object is inserted through the InsertAfter method after all the nodes of class equals inner
The meaning of the expression is the same as after, the main difference is the grammar-especially the position of the content and the target
Jquery.fn[ name ] = function ( selector ) { var Elems, ret = [], insert = jquery ( selector ),
Last = insert.length - 1, i = 0; for ( ; i <= last; i++ ) { elems = i === last ? this :
This.clone ( true ); jquery ( insert[ i ] ) [ original
] ( elems ); // support: qtwebkit // .get () because core_push.apply (_, arRaylike) throws core_push.apply ( ret, elems.get (
) );
&NBSP;&NBSP;&NBSP;&NBSP} return this.pushstack ( ret ); };
See the specific implementation method. InsertAfter ('. inner '); Inner was actually introduced as selector.
Selector may just have to be transformed inside the string selector, insert = JQuery (selector),
$ (' <p>Test</p> ') is a constructed document fragment node, so if you give the insert multiple times you need to completely clone a copy, so you directly assign
Elems = i = = last? This:this.clone (TRUE); JQuery (insert[i]) [original] (Elems);
is still the execution after
JQuery (insert[i]) [original] (Elems);
Eventually, you need to return to the new node for this build.
Collect the built nodes
Core_push.apply (ret, elems.get ());
Build a new jquery object to implement the chained
This.pushstack (ret);
It can be seen that the essence of after and InsertAfter is the same, but in different ways
Before ()
Inserts the content before the matching element, based on the parameter settings
Before:function () {return
this.dommanip (arguments, function (elem) {
if (this.parentnode ) {
This.parentNode.insertBefore (elem, this);
}
});
},
Like after just replacing the second parameter, changing the insertion position
Append ()
Inserts the parameter contents at the end of each matching element
Append:function () {return
this.dommanip (arguments, function (elem) {
if This.nodetype = 1 | | His.nodetype = = 11 | | This.nodetype = = 9 {
var target = Manipulationtarget (this, elem);
Target.appendchild (elem);
}
});
},
To add nodes internally, you can call the AppendChild method directly
Prepend ()
Inserts the parameter contents before each matching element (inside the element)
Prepend:function () {return
this.dommanip (arguments, function (elem) {
if (This.nodetype = 1 | | This.nodetype = = 11 | | This.nodetype = = 9 {
var target = Manipulationtarget (this, elem);
Target.insertbefore (Elem, target.firstchild);
}
});
},
Like after just replacing the second parameter, changing the insertion position
ReplaceWith ()
Replaces all matching elements in the collection with the provided content and returns a collection of deleted elements.
. ReplaceWith () can remove content from the DOM and insert new content in this place. Take a look at the following example:
<div class= "Container" >
<div class= "inner A" >Hello</div>
<div class= "inner second" >And</div>
<div class= "inner third" >Goodbye</div>
</div>
We can replace the second inner <div> with the specified HTML:
$ (' Div.second '). ReplaceWith ('
The results are as follows:
<div class= "Container" >
<div class= "inner A" >Hello</div>
Or we can choose an element to take it as a replacement:
$ (' Div.third '). ReplaceWith ($ ('. a '));
The results are as follows:
<div class= "Container" >
<div class= "inner second" >And</div>
<div class= "inner a" >Hello</div>
</div>
As you can see from this example, the elements used to replace are moved from the old place to the new location, rather than copied.
The. ReplaceWith () method, like most other jquery methods, returns the JQuery object, so it can be used with other methods, but it should be noted that for this method, the object points to an object that has been removed from the DOM, rather than to the replacement object.
Replacewith: function () { var snapshot the dom in case .dommanip sweeps something relevant into its fragment args = jquery.map ( this, function ( elem ) {
return [ elem.nextSibling, elem.parentNode ]; &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP}), i =
0; // make the changes, replacing each context element with the new content this.dommanip ( arguments, function ( elem ) { var next = args[ i ++ ], &NBSP;&NBSP;&NBSP;&NBsp; parent = args[ i++ ]; if ( parent ) { // don ' t use the snapshot next if it has moved (#13810) if ( next && next.parentNode !== parent ) { next =
this.nextsibling; }
jquery ( this ). Remove (); parent.insertbefore ( elem,
next ); } // Allow new content to include elements from
The context set }, true ); // force removal if there was no new content (e.g., from empty arguments) return i ? this :
this.remove (); },
Deletes the target node
JQuery (this). Remove ();
and then insert a new node
Parent.insertbefore (Elem, next);