Some of these pieces of code are supported by jQuery1.4.2 and others are really useful functions or methods that can help you get things done quickly and well. These are the best performance snippets I've ever tried to remember, so if you find anything you can do better, please paste your version in the comments! I hope you can find something helpful in this article.
Jquery.preloadimages = function () {
for (var i = 0; i < arguments.length; i++) {
$ ("
16. How to set an event handler for any element that matches the selector:
$ (' Button.someclass '). Live (' click ', someFunction);
Note that in the jquery 1.4.2, the delegate and undelegate options
//are introduced instead of live because they provide better contextual support
//For example, in the case of table, you used to use
//.live ()
$ ("table"). each (function () {
$ (' TD ', this '). Live ("hover", function () {
$ (this). Toggleclass ("hover");
});
});
Now use
$ ("table"). Delegate ("TD", "hover", function () {
$ (this). Toggleclass ("hover");
17. How to find an option element that has already been selected:
$ (' #someElement '). Find (' option:selected ');
18. How to hide an element that contains the text of a value:
$ ("P.value:contains (' Thetextvalue ')"). Hide ();
19. How to automatically scroll to an area in the page
JQuery.fn.autoscroll = function (selector) {
$ (' html,body '). Animate (
{scrolltop: $ (selector). Offset (). Top},
}
;
}
Then scroll like this to the class/area you want to go to.
$ ('. Area_name '). AutoScroll ();
20. How to detect various browsers:
Detect Safari (if ($.browser.safari)),
detect IE6 and later versions (if ($.browser.msie && $.browser.version > 6)),
Detects IE6 and previous versions (if ($.browser.msie && $.browser.version <= 6),
detects Firefox 2 and later versions (if ($.browser.mozilla ;& $.browser.version >= ' 1.8 '))
21. How to replace the words in a string
var el = $ (' #id ');
El.html (el.html (). Replace (/word/ig, '));
22. How to disable right-click context menu:
$ (document). Bind (' ContextMenu ', function (e) {return
false;
});
23. How to define a custom selector
$.expr[': '].mycustomselector = function (element, index, meta, stack) {
//element-
The current cyclic index in a DOM element//index– Stack c4/>//meta–///
stack– the stack of all elements to loop///If the
current element is included returns True
//returns False if the current element is not included;
Custom Selector Usage:
$ ('. Someclasses:test '). dosomething ();
24. How to check if an element exists
if ($ (' #someDiv '). Length) {
//Long live!!! It exists ...
}
25. How to use jquery to detect two mouse clicks with right and left buttons:
$ ("#someelement"). Live (' click ', Function (e) {
if (!$.browser.msie && e.button = 0) | | ($.browser.msie && E.button = 1)) {
alert ("Left Mouse button clicked");
} else if (E.button = = 2) {
alert ("Right Mouse button clicked");
}
);
26. How to display or delete the default values in the input field
This code shows
how to keep//
a default value
wap_val = []
in the input field of the text type when the user does not enter a value. $ (". Swap"). each (function (i) {
wap_val[i] = $ (this). Val ();
$ (this). Focusin (function () {
if ($ (this). val () = = Wap_val[i]) {
$ (this). Val ("");
}
). Focusout (function () {
if ($.trim ($ (this). val ()) = = "") {
$ (this). Val (Wap_val[i]);
}
}
);
<input type= "text" value= "Enter Username here ..." class= "swap"/>
27. How to automatically hide or close elements after a period of time (support version 1.4):
This is the way we use settimeout to implement in 1.3.2
settimeout (function () {
$ ('. Mydiv '). Hide (' blind ', {},)
}, 5000);
This is the way that you can use the delay () feature in 1.4 (which is much like hibernation)
$ (". Mydiv"). Delay (5000). Hide (' blind ', {}, 500);
28. How to dynamically add elements that have been created to the DOM:
var newdiv = $ (');
NEWDIV.ATTR (' id ', ' mynewdiv '). Appendto (' body ');
29. How to limit the number of characters in the "Text-area" field:
JQuery.fn.maxLength = function (max) {This.each (function () {var type = This.tagName.toLowerCase (); var inputtype = This.type?
This.type.toLowerCase (): null;
if (type = = "Input" && inputtype = = "Text" | | | inputtype = = "Password") {//apply standard maxLength
This.maxlength = max;
else if (type = = "textarea") {this.onkeypress = function (e) {var ob = e | | | event;
var keycode = Ob.keycode; var hasselection = document.selection?
Document.selection.createRange (). text.length > 0:this.selectionstart!= this.selectionend; Return! (This.value.length >= Max && (KeyCode > | | keycode = | | keycode = 0 | | keycode =) &&!ob
. Ctrlkey &&!ob.altkey &&!hasselection);
};
This.onkeyup = function () {if (This.value.length > Max) {this.value = this.value.substring (0,max);
}
};
}
});
}; Usage $ (' #mytextarea '). MaxLength (500);
30. How to create a basic test for a function
Separate the tests into modules
("Module B");
Test ("Some other test", function () {
//Indicates how many assertions are expected to run within the test
expect (2);
A comparison assertion, equivalent to JUnit's Assertequals
equals (True, false, "failing test");
Equals (True, true, "passing Test");
});
31. How to clone an element in jquery:
var cloned = $ (' #somediv '). Clone ();
32. How to test whether an element is visible in jquery
if ($ (Element). Is (': visible ') = = ' true ') {
//The element is visible
}
33. How to place an element in the center of the screen:
JQuery.fn.center = function () {
this.css (' position ', ' absolute ');
This.css (' Top ', ($ (window). Height ()-this.height ())/2 +$ (window). scrolltop () + ' px ');
This.css (' Left ', ($ (window). Width ()-this.width ())/2 +$ (window). ScrollLeft () + ' px ');
return this;
}
This allows you to use the above function:
$ (Element). Center ();
34. How to put the values of all elements that have a particular name in an array:
var arrinputvalues = new Array ();
$ ("Input[name= ' table[]"). each (function () {
Arrinputvalues.push ($ (this). Val ());
});
35. How to remove HTML from an element
(function ($) {
$.fn.striphtml = function () {
var regexp =/< ("[^"]* "|") [^']*'| [^ ' "]) *>/gi;
This.each (function () {
$ (this). HTML ($ (this). html (). Replace (RegExp, ""));
return $ (this);
}
}) (jQuery);
Usage:
$ (' P '). striphtml ();
36. How to use closest to get the parent element:
$ (' #searchBox '). Closest (' div ');
37. How to use Firebug and Firefox to record the jquery event log:
Allow chained logging
//Usage:
$ (' #someDiv '). Hide (). log (' div hidden '). addclass (' SomeClass ');
JQuery.log = JQuery.fn.log = function (msg) {
if (console) {
console.log ("%s:%o", MSG, this);
}
return this;
};
38. How to force a link to open in a pop-up window:
JQuery (' A.popup '). Live (' click ', Function () {
Newwindow=window.open (this). attr (' href '), ', ' height=200, Width=150 ');
if (window.focus) {
newwindow.focus ();
}
return false;
});
39. How to force the link to open in a new tab:
JQuery (' A.newtab '). Live (' click ', Function () {
Newwindow=window.open ($ (this). href);
JQuery (this). target = "_blank";
return false;
});
40. How to use. Siblings () in jquery to select sibling elements
Do not do this
$ (' #nav li '). Click (function () {
$ (' #nav Li '). Removeclass (' active ');
$ (this). addclass (' active ');
};
The alternative is
$ (' #nav li '). Click (function () {
$ (this). addclass (' active '). Siblings (). Removeclass (' active ');
});
41. How to toggle all check boxes on the page:
var tog = false;
Or True if they are selected when they are loaded
$ (' a '). Click (function () {
$ ("Input[type=checkbox]"). attr ("Checked",!tog);
Tog =!tog;
});
42. How to filter a list of elements based on some input text:
If the value of the element matches the input text
//The element will be returned
$ ('. SomeClass '). Filter (function () {return
$ (this). attr (' value ') = = $ (' Input#someid '). Val ();
})
43. How to get mouse pad cursor position x and Y
$ (document). Ready (function () {
$ (document). MouseMove (function (e) {
$ (' #XY '). HTML ("X Axis: + E.pagex +" | Y Axis "+ e.pagey);
}";
44. How to turn the entire list element (Element,li) into a clickable
$ ("ul Li"). Click (function () {
window.location=$ (this). Find ("a"). attr ("href");
return false;
});
<ul>
<li><a href= "#" >link 1</a></li>
<li><a href= "#" >link 2 </a></li>
<li><a href= "#" >link 3</a></li>
<li><a "#" >link 4</a></li>
</ul>
45. How to use jquery to parse XML (basic example):
function Parsexml (XML) {
//finds each Tutorial and prints out author
$ (XML). Find ("Tutorial"). each (function () {
$ ("# Output "). Append ($ (this). attr (" author ") +" ");}
46. How to check if the image has been fully loaded in
$ (' #theImage '). attr (' src ', ' image.jpg '). Load (function () {
alert (' This image has Been Loaded ');
});
47. How to use jquery to specify namespaces for events:
Events can thus bind the namespace
$ (' input '). Bind (' Blur.validation ', function (e) {
//...
});
The data method also accepts
the namespace $ (' input '). Data (' Validation.isvalid ', true);
48. How to check whether cookies are enabled
var dt = new Date ();
Dt.setseconds (Dt.getseconds () +);
Document.cookie = "cookietest=1; Expires= "+ dt.togmtstring ();
var cookiesenabled = document.cookie.indexOf ("cookietest=")!=-1;
if (!cookiesenabled) {
//No cookies enabled
}
49. How to expire cookies:
var date = new Date ();
Date.settime (Date.gettime () + (x * * 1000));
$.cookie (' Example ', ' foo ', {expires:date});
50. How to use a clickable link to replace any URL in the page
$.fn.replaceurl = function () {
var regexp =/(FTP|HTTP|HTTPS): \/\/(\w+:{0,1}\w*@)? ( \s+) (: [0-9]+)? (\/|\/([\w#!:.? +=&%@!\-\/])? /gi;
This.each (function () {
$ (this). HTML (
$ (this). html (). Replace (RegExp, ' <a href= ' >$1</a> ')
);
});
return $ (this);
}
Usage
$ (' P '). Replaceurl ();
Just tidy up so much.
If you are not satisfied, we recommend that you look at the Super Practical jquery Code section of the book. The cloud-dwelling community has exactly the PDF version. Everyone can see.