What are the jQuery code development skills?
This article is to share with you about jQuery code development skills, the editor feels very practical, so share with you to learn, I hope you can get something after reading this article, say no more, follow the editor to have a look.
1. Create a nested filter
.filter (": not (: has (.selected))") / / remove all elements that do not contain elements whose class is .selected
two。 Reuse your element query
Var allItems = $("div.item"); var keepList = $("div#container1 div.item"); class names: $(formToLookAt + "input:checked") .each (function () {keepListkeepList = keepList.filter ("." + $(this) .attr ("name"));})
3. Use has () to determine whether an element contains a specific class or element
/ / jQuery 1.4.* includes support for the has method. This method will find / / if an an element contains a certain other element class or whatever it is / / you are looking for and do anything you want to them. $("input") .has (".email") .addClass ("email_icon")
4. Use jQuery to switch styles
/ / Look for the media-type you wish to switch then set the href to your new style sheet $('link [media =' screen']') .attr ('href',' Alternative.css')
5. Restrict the selected area
/ / Where possible, pre-fix your class names with a tag name / / so that jQuery doesn't have to spend more time searching / / for the element you're after. Also remember that anything / / you can do to be more specific about where the element is / / on your page will cut down on execution/search times var in_stock = $('# shopping_cart_items input.is_in_stock'); Item X Item Y Item Z
6. How to use ToggleClass correctly
/ / Toggle class allows you to add or remove a class / / from an element depending on the presence of that / / class. Where some developers would use: a.hasClass ('blueButton')? A.removeClass ('blueButton'): a.addClass (' blueButton'); / / toggleClass allows you to easily do this using a.toggleClass ('blueButton')
7. Set the function specified by IE
If ($.browser.msie) {/ / Internet Explorer is a sadist. }
8. Use jQuery to replace an element
$('# thatdiv'). ReplaceWith ('fnuh')
9. Verify that an element is empty
If ($('# keks'). Html ()) {/ / Nothing found;}
10. Find the index of an element in an unordered set
$("ul > li") .click (function () {var index = $(this). PrevAll () .length;})
11. Bind a function to an event
$('# foo') .bind ('click', function () {alert (' User clicked on "foo.");})
twelve。 Add HTML to an element
$('# lal'). Append ('sometext')
13. Use objects to define attributes when creating elements
Var e = $("", {href: "#", class: "a-class another-class", title: "..."})
14. Filter multiple attributes using a filter
/ / This precision-based approached can be useful when you use / / lots of similar input elements which have different types var elements = $('# someid input [type=sometype] [value=somevalue]') .get ()
15. Use jQuery to preload pictures
JQuery.preloadImages = function () {for (var I = 0; i'). Attr ('src', arguments [I]);}}; / / Usage $.preloadImages (' image1.gif','/ path/to/image2.png', 'some/image3.jpg')
16. Set up any event handlers that match a selector
$('button.someClass'). Live (' click', someFunction); / / Note that in jQuery 1.4.2, the delegate and undelegate options have been//introduced to replace live as they offer better support for context//For example, in terms of a table where before you would use..// .live () $("table") .each (function () {$("td", this) .live ("hover", function () {$(this) .toggleClass ("hover");}) / / Now use..$ ("table") .delegate ("td", "hover", function () {$(this) .toggleClass ("hover");})
17. Find the selected option (option) element
$('# someElement'). Find ('option:selected')
18. Hide elements that contain specific values
$("p.value:contains ('thetextvalue')") .hide ()
19. Automatically scroll to a specific area of the page
JQuery.fn.autoscroll = function (selector) {$('html,body') .animate ({scrollTop: $(selector). Offset (). Top}, 500);} / / Then toscroll to the class/area you wish to get to like this:$ (' .area _ name') .autoscroll ()
20. Detect various browsers
Detect Safari (if ($.browser.safari)), Detect IE6 and over (if ($.browser.msie & & $.browser.version > 6), Detect IE6 and below (if ($.browser.msie & & $.browser.version = '1.8'))
21. Replace words in a string
Var el = $('# id'); el.html (el.html (). Replace (/ word/ig,'))
twenty-two。 Close the right-click menu
$(document) .bind ('contextmenu',function (e) {return false;})
23. Define a custom selector
Mycustomselector = function (element, index, meta, stack) {/ / element- is a DOM element// index-the current loop index in stack// meta-meta data about your selector// stack-stack of all elements to loop// Return true to include current element// Return false to explude current element}; / / Custom Selector usage:$ ('.someClasses: test') .expr ()
24. Determine whether an element exists or not
If ($('# someDiv'). Length) {/ / hoorayflowers! It exists...}
25. Use jQuery to judge the left and right click of the mouse.
$("# 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");})
twenty-six。 Show or delete the default value of the input box / / This snippet will show you how to keep a default value//in a text input field for when a user hasn't entered in//a value to replace itswap_val = []; $(".swap") .each (function (I) {swap_ vale [I] = $(this) .val (); $(this) .focusin (function () {if ($(this). Val () = swap_ vale [I]) {$(this) .val ("")) ) .focusout (function () {if ($.trim ($(this). Val ()) = "") {$(this) .val (swap_ vale [I]);});}); 27. Automatically hide or close elements after specified time / / Here's how we used to do it in 1.3.2 using setTimeoutsetTimeout (function () {$('.mydiv'). Hide ('blind', {}, 5000); / / And here's how you can do it with 1.4using the delay () feature (this is a lot like sleep) $(".mydiv") .delay (5000) .hide (' blind', {}, 5000); 28. Dynamically create elements to DOMvar newgbin1Div = $(''); newgbin1Div.attr ('id','gbin1.com'). AppendTo (' body'); 29. Limit the number of characters in textarea 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 the standard maxLengththis.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 > 50 | keyCode = = 32 | | keyCode = = 0 | | keyCode = = 13) & &! ob.ctrlKey & &! ob.altKey &! hasSelection);}; this.onkeyup = function () {if (this.value.length > max) {this.value = this.value.substring;};});} / / Usage:$ ('# gbin1textarea'). MaxLength (500); 30. Create a basic test case for the function / / Separate tests into modules.module ("Module B"); test ("some other gbin1.com test", function () {/ / Specify how many assertions are expected to run within a test.expect (2); / / A comparison assertion, equivalent to JUnit's assertEquals.equals (true, false, "failing test"); equals (true, true, "passing test");}); 31. Use jQuery to clone element var cloned = $('# gbin1div'). Clone (); 32. Test whether an element is visible in jQuery if ($(element). Is (': visible') = = 'true') {/ / The element is Visible} 33. Element screen centered jQuery.fn.center = function () {this.css ('position','absolute'); this.css (' top', ($(window). Height ()-this.height ()) / + $(window). ScrollTop () + 'px'); this.css (' left', ($(window). Width ()-this.width ()) / 2 percent $(window). ScrollLeft () + 'px'); return this } / / Use the above function as: $('# gbin1div'). Center (); 34. Generate an array var arrInputValues = new Array (); $("input [name = 'table []']") .each (function () {arrInputValues.push ($(this). Val ());}); 35. Remove HTML (function ($) {$.fn.stripHtml = function () {var regexp = /]) * > / gi;this.each (function () {$(this). Html ($(this). Html (). Replace (regexp, ");}); return $(this);}) (jQuery); / / usage:$ ('p'). StripHtml (); 36. Use closest to get the parent element $('# searchBox'). Closest ('div'); 37. Use firebug to log jQuery events / / Allows chainable 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. Click the link to force a new 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. Click the link to force a new tab jQuery ('a.newTab'). Live ('click', function () {newwindow=window.open ($(this) .href); jQuery (this). Target = "_ blank"; return false;}); 40. Use siblings () to process similar elements / / Rather than doing this$ ('# nav li') .click (function () {$('# nav li'). RemoveClass ('active'); $(this) .addClass (' active');}); / / Do this instead$ ('# nav li') .click (function () {$(this) .addClass ('active'). Siblings (). Click (' active');}); 41. Select or deselect all the check boxes on the page var tog = false; / / or true if they are checked on load$ ('a') .click (function () {$("input [type=checkbox]"). Attr ("checked",! tog); tog =! tog;}); 42. Filter the page element / / If the value of the element matches that of the entered text//it will be returned$ ('.gbin1Class') .filter (function () {return $(this) .attr ('value') = = $(' input#gbin1Id'). Val ();}) 43. Get the X and Y coordinates of the mouse $(document) .mousemove (function (e) {$(document) .ready (function () {$() .mousemove (function (e) {$('# XY') .html ("Gbin1 X Axis:" + e.pageX + "| Gbin1 Y Axis" + e.pageY);}); 44. Make the entire list element (LI) clickable to $("ul li") .click (function () {_ window.location=$ (this). Find ("a"). Attr ("href"); return false;}); GBin1 Link 1GBin1 Link 2GBin1 Link 3GBin1 Link 4 45. Use jQuery to parse XMLfunction parseXml (xml) {/ / find every Tutorial and print the author$ (xml). Find ("Tutorial") .each (function () {$("# output"). Append ($(this) .attr ("author") + ");} 46. Determine whether a picture is fully loaded with $('# theGBin1Image'). Attr ('src',' image.jpg') .load (function () {alert ('This Image Has Been Loaded');}); 47. Use jQuery to name the event / / Events can be namespaced like this$ ('input'). Bind (' blur.validation', function (e) {/ /...}); / / The data method also accept namespaces$ ('input'). Data (' validation.isValid', true); 48. Determine whether cookie activates or closes var dt = new Date (); dt.setSeconds (dt.getSeconds () + 60); [xss_clean] = "cookietest=1; expires=" + dt.toGMTString (); var cookiesEnabled = [xss_clean] .indexOf ("cookietest=")! =-1 xss_clean if (! cookiesEnabled) {/ / cookies have not been enabled} 49. Forced expiration cookievar date = new Date (); date.setTime (date.getTime () + (x * 60 * 1000)); $.cookie ('example',' foo', {expires: date}); 50. Use a clickable link to replace all URL$.fn.replaceUrl = function () {var regexp = / ((ftp | http | https): / / (wicked: {0jue 1} wicked @)? (S+) (: [0-9] +)? (/ / ([washable flowers. Horse flowers% this /])?) / gi;this.each (function () {$(this). Html ($(this). Html (). Replace (regexp,'$1'));}) Return $(this);} / usage$ ('# GBin1div'). ReplaceUrl (); these are all the jQuery code development skills, and the editor believes that there are some knowledge points that we may see or use in our daily work. I hope you can learn more from this article. For more details, please follow the industry information channel.