1. Execute JavaScript code when document documentation is ready.
Why do we use the jquery library? One reason is that we can make jquery code work perfectly in a variety of browsers and bug-prone browsers.
<script src= "Http://code.jquery.com/jquery-1.10.2.min.js" ></script>
<script>
/ Different ways to achieve of the document Ready event
//With JQuery
$ (Document). Ready (function () {/* ... */});
Short JQuery
$ (function () {/* ... */});
Without jQuery (doesn ' t work in older IE versions)
document.addeventlistener (' domcontentloaded ', function () {
//Your code goes here
});
The TrickShot (works everywhere):
R (function () {
alert (' DOM ready! ');
})
function r (f) {/in/.test (document.readystate)? SetTimeout (' R (' +f+ ') ', 9): F ()}
</script>
2. Use route.
<script src= "Http://code.jquery.com/jquery-1.10.2.min.js" ></script>
<script>
var route = {
_routes: {},//The routes'll be stored here
add:function (URL, action) {
This._routes[url] = action;
},
run:function () {
Jquery.each (this._routes, function (pattern) {
if (location.href.match) {
//' This ' points to the ' function to ' is executed this
();
}
}} Would execute only on this page:
route.add (' 002.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 (' The ' is using a regex! ')
});
Route.run ();
</script>
3. Use and techniques in JavaScript.
The use of the && operator is that if the expression on the left side of the operator is false, it will no longer judge the expression on the right side of the operator. So:
Instead of writing this:
if ($ (' #elem '). Length) {
//does something
}
//You can write this:
$ (' # Elem '). Length && log ("doing something");
4. The IS () method is more powerful than you think.
Here are a few examples, we first write a div with ID elem. The JS code is as follows:
The cache the element into a variable:
var elem = $ (' #elem ');
Is this a div?
Elem.is (' div ') && log ("It ' s a div");
Does it have the BigBox class?
Elem.is ('. BigBox ') && log ("It has the BigBox class!");
Is it visible? (We are hiding it in this example)
Elem.is (': Not (: visible) ') && log ("It is hidden!");
Animating
elem.animate ({' width ': 200},1);
Is it animated?
Elem.is (': Animated ') && log ("It is animated!");
I think it's very good to see if it's animated.
5. Determine how many elements you have on your Web page.
By using the $ ("*"). Length (), the method can determine the number of elements in the page.
How many elements does your page have?
Log (' This page has ' + $ (' * '). Length + ' elements! ');
6. Using the length () property is cumbersome, we use the exist () method below.
/Old way
log ($ (' #elem '). length = = 1? "exists!": "Doesn ' t exist!");
TrickShot:
jQuery.fn.exists = function () {return this.length > 0;}
Log ($ (' #elem '). Exists ()? "exists!": "Doesn ' t exist!");
The 7.jQuery Method $ () actually has two parameters, do you know the function of the second parameter?
Select an element. The second argument is context to limit the search
//can use a selector, JQuery object or DOM element
$ (' Li ', ' #firstList '). each (the function () {
log ($ (this). html ()
); Log ('-----');
Create an element. The second argument
is a//object with JQuery methods to be called
var div = $ (' <div> ', {
"class '):" Big Blue "
css": {
"background-color": "Purple"
},
"width": "
height": "
animate" : {//You can use any JQuery method as a property!
" Width ":",
"height":}
);
Div.appendto (' #result ');
8. Using jquery we can determine whether a link is external and to add an icon in a non external link and determine how to open it.
The hostname attribute is used here.
<ul id= "Links" >
<li><a href= "007.html" >the previous tip</a></li>
<li> <a href= "./009.html" >the next tip</a></li> <li><a href=
"http://www.google.com/" > google</a></li>
</ul>
//Loop through all of the links
$ (' #links a '). each (function () {
if (this.hostname!= location.hostname) {
//the link is external
$ (this). Append ('
The end () method in 9.jQuery can make your jquery chain more efficient.
<ul id= "Meals" > <li> <ul class= "Breakfast" > <li class= "eggs" >No</li> <li class= "toast ">No</li> <li class=" Juice ">No</li> </ul> </li> </ul>//Here are how it's use
D:
var breakfast = $ (' #meals. Breakfast ');
Breakfast.find ('. Eggs '). Text (' yes '). End
()//back to breakfast
. Find ('. Toast '). Text (' Yes ')
. Find ('. Juice '). Toggleclass (' Juice coffee '). Text (' Yes ');
Breakfast.find (' Li '). each (function () {
log (this.classname + ': ' + this.textcontent)
});
10. You may want your Web application to feel more like native, so you can block the ContextMenu default event.
<script>
//Prevent right clicking in this page
$ (function () {
$ (document). On ("ContextMenu", Function (e) {
e.preventdefault ();
}
); </script>
11. Some sites may make your page below a bar, which we see in the following page is the IFRAME tag, we can solve this.
This is used:
if (Window!= window.top) {
window.top.location = window.location;
}
else{
alert (' This page isn't displayed in a frame. Open 011.html to, it in action.
12. Your inline style sheet is not set to be immutable , as follows:
Make the stylesheet visible and editable
$ (' #regular-style-block '). CSS ({' Display ': ' Block ', ' white-space ': ' Pre '}]
. attr (' contenteditable ', true);
This changes the inline style.
13. Sometimes we don't want a certain part of the page to be selected, such as copying and pasting , and we can do this:
<p class= "DESCR" >in certain situations you might to want text on the page from prevent being. Try Selecting this text and hit view source-to-do it is done.</p>
<script>
//Prevent text from B Eing selected
$ (function () {
$ (' p.descr '). attr (' unselectable ', ' on ').
css (' user-select ', ' none ')
. On (' Selectstart ', false);
};
</script>
In this way, the content can not be selected.
14. The introduction of jquery from a CDN would improve the performance of our site, and it would be a good idea to introduce the latest version.
Here are four different ways to do this.
<!--case 1-requesting JQuery official CDN-->
<script src= "http://code.jquery.com/jquery-1.10.2. Min.js "></script>
<!--case 2-requesting jQuery from Google ' CDN (Notice the Protocol)--> <!
--<script src= "//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" ></script>-->
<!--case 3-requesting The latest minor 1.8.x version (only cached for a hour)-->
<!--<script src= "/ Ajax.googleapis.com/ajax/libs/jquery/1.10/jquery.min.js "></script>-->
<!--case 4-requesting The absolute latest jQuery version (use with caution)-->
<!--<script src= "http://code.jquery.com/ Jquery.min.js "></script>-->
15. Ensure minimal DOM operation.
We know that JS Operation Dom is a waste of resources, we can look at the following example.
CODE
//Bad
//var elem = $ (' #elem ');
for (var i = 0; i < i++) {
//elem.append (' <li>element ' +i+ ' </li> ');
}
//good
var elem = $ (' #elem '),
arr = [];
for (var i = 0; i < i++) {
arr.push (' <li>element ' +i+ ' </li> ');
}
Elem.append (Arr.join ('));
16. More convenient decomposition URL.
You may be using regular expressions to parse URLs, but this is definitely not a good way to use a tag to implement it.
You are want to parse this address into parts:
var url = ' Http://tutorialzine.com/books/jquery-trickshots?trick=12#co Mments ';
The trickshot:
var a = $ (' <a> ', {href:url});
Log (' Host name: ' + a.prop (' hostname '));
Log (' Path: ' + a.prop (' pathname '));
Log (' Query: ' + a.prop (' search '));
Log (' Protocol: ' + a.prop (' Protocol '));
Log (' hash: ' + a.prop (' hash '));
17. Don't be afraid to use vanilla.js.
jquery is saddled with too much, which is why you can use the generic JS.
Print The IDs of all LI items
$ (' #colors Li '). each (function () {
//Access the ID directly, instead
//of USI Ng JQuery ' s $ (this). attr (' id ')
log (this.id);
18. Optimize your Selector
Let ' s try some benchmarks!
var iterations = 10000, I;
Timer (' Fancy ');
for (I=0 i < iterations, i++) {
//This falls back to a slow JavaScript DOM traversal
$ (' #peanutButter Div:fir St ');
Timer_result (' Fancy ');
Timer (' Parent-child ');
for (i=0 i < iterations; i++) {
//Better, but still slow
$ (' #peanutButter div ');
}
Timer_result (' Parent-child ');
Timer (' Parent-child by class ');
for (i=0 i < iterations i++) {
//Some browsers are a bit faster on this one
$ (' #peanutButter. Jellytime ')
19. Cache your selector.
Bad:
//$ (' #pancakes li ')-eq (0). Remove ();
$ (' #pancakes li '). EQ (1). Remove ();
$ (' #pancakes li '). EQ (2). Remove ();
Good:
var pancakes = $ (' #pancakes Li ');
Pancakes.eq (0). Remove ();
Pancakes.eq (1). Remove ();
Pancakes.eq (2). Remove ();
Alternatively:
//Pancakes.eq (0). Remove (). End ()
//. EQ (1). Remove (). End ()
//. EQ (2). Remove (). End ( );
20. For duplicate functions, define only once
If you're looking for more high-performance code, you have to be careful when you set up the event listener, it's a good idea to define the function once and pass its name as an event handler.
$ (document). Ready (function () {
function ShowMenu () {
alert (' showing menu! ');
Doing something complex here
}
$ (' #menuButton '). Click (showmenu);
$ (' #menuLink '). Click (showmenu);
21. Treat jquery objects like arrays
Because the jquery object has the index value and the length, this means that we can treat the object as a normal array. This will also have better performance.
var arr = $ (' li '),
iterations = 100000;
Timer (' Native Loop ');
for (Var z=0;z<iterations;z++) {
var length = arr.length;
for (var i=0 i < length; i++) {
arr[i]}
}
Timer_result (' Native Loop ');
Timer (' JQuery each ');
for (z=0;z<iterations;z++) {
Arr.each (function (i, Val) {this
;
});
Timer_result (' JQuery each ');
Not to be continued ...
The above is the entire content of this article, I hope the content of this article for everyone's study or work can bring some help, but also hope that a lot of support cloud Habitat community!