Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the necessary practical jQuery code snippets

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article shows you what the necessary practical jQuery code snippets are, which are concise and easy to understand, which can definitely brighten your eyes. I hope you can get something through the detailed introduction of this article.

The editor will show you 50 jquery code snippets that can help your javascript project. Some of these code snippets are supported since jQuery1.4.2, while others are really useful functions or methods that can help you get things done quickly and well.

1. How to create a nested filter:

/ / allows you to reduce the filters of matching elements in the collection, / / only those that match a given selector are left. In this case, the / / query removes any child nodes with or without (: not) with (: has) / / containing the class as "selected" (. Selected). .filter (": not (: has (.selected)")

two。 How to reuse element search

Var allItems = $("div.item"); var keepList = $("div#container1 div.item"); / / now you can continue to work with these jQuery objects. For example, / / crop "keep list" based on the check box, the name of the check box matches / /

< DIV >

Class names: $(formToLookAt + "input:checked") .each (function () {keepList = keepList.filter ("." + $(this) .attr ("name"));})

< /DIV>

3. Anyone who uses has () to check whether an element contains a class or element:

/ / jQuery 1.4.* includes support for this has method. This method finds out whether / / an element contains another element class or anything else you are looking for and operating on. $("input") .has (".email") .addClass ("email_icon")

4. How to use jQuery to switch style sheets

/ / find out the type of media you want to switch (media-type) and set href to the new stylesheet. $('Linkmedia =' screen']') .attr ('href',' Alternative.css')

5. How to limit the scope of selection (for optimization purposes):

/ / use tag signatures as prefixes to class names whenever possible

/ / so that jQuery does not need to spend more time searching

/ / the elements you want. One more thing to remember is that

/ / the more specific actions are directed at the elements on your page

/ / the more time it takes to execute and search.

Var in_stock = $('# shopping_cart_items input.is_in_stock')

Item X

Item Y

Item Z

6. How to use ToggleClass correctly:

/ / switching (toggle) class allows you to add or remove a class based on its / / existence. / / in this case, some developers use a.hasClass ('blueButton')? A.removeClass ('blueButton'): a.addClass (' blueButton'); / / toggleClass allows you to easily do this a.toggleClass ('blueButton') using the following statement

7. How to set IE-specific features:

If ($.browser.msie) {/ / Internet Explorer is a sadist}

8. How to use jQuery instead of an element:

$('# thatdiv'). ReplaceWith ('fnuh')

9. How to verify that an element is empty:

If ($('# keks'). Html ()) {/ / nothing was found;}

10. How to find the index number of an element from an unsorted collection

$("ul > li") .click (function () {var index = $(this). PrevAll () .length;})

11. How to bind a function to an event:

$('# foo') .bind ('click', function () {alert (' User clicked on "foo.");})

twelve。 How to append or add html to an element:

$('# lal'). Append ('sometext')

13. How to use object literals (literal) to define attributes when creating elements

Var e = $("", {href: "#", class: "a-class another-class", title: "..."})

14. How to use multiple attributes for filtering

/ / this precision-based approach is useful when using many similar input elements with different types, var elements = $('# someid input [type=sometype] [value=somevalue]') .get ()

15. How to use jQuery to preload an image:

JQuery.preloadImages = function () {for (var I = 0; I)

< arguments.length; i++) { $("

"). Attr ('src', arguments [I]);}}; / / usage $.preloadImages (' image1.gif','/ path/to/image2.png', 'some/image3.jpg')

16. How to set an event handler for any element that matches the selector:

$('button.someClass'). Live (' click', someFunction) / Note that in jQuery 1.4.2, the delegate and undelegate options / / are introduced instead of live because they provide better context support / / for example, in the case of table, you would have used / / .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 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. If you automatically scroll to an area of the page

JQuery.fn.autoscroll = function (selector) {$('html,body') .animate ({scrollTop: $(selector). Offset (). Top}, 500};} / then scroll to the class/area you want to go to like this. $('.area _ name') .autoscroll ()

20. How to detect various browsers:

Detect Safari (if ($.browser.safari), IE6 and later versions (if ($.browser.msie & & $. Browser.version > 6), IE6 and previous versions (if ($.browser.msie & $. Browser.version = '1.8'))

21. How to replace words in a string

Var el = $('# id'); el.html (el.html (). Replace (/ word/ig,'))

twenty-two。 How to disable the right-click context menu:

$(document) .bind ('contextmenu',function (e) {return false;})

23. How to define a custom selector

Mycustomselector [':'] .expr = function (element, index, meta, stack) {/ / element- an DOM element / / index-current circular index in the stack / / meta-metadata about selector / / stack-stack of all elements to loop / stack / return true if it contains the current element / / return false} if it does not contain the current element / / usage of custom selector: $('.someClasses: test') .doSomething ()

24. How to check whether an element exists

If ($('# someDiv'). Length) {/ / long live! It exists... }

25. How to use jQuery to detect right and left mouse clicks:

$("# 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。 How to display or delete default values in input fields

/ / this code shows how to leave / / a default value of wap_val = [] in the text type input field when the user does not enter a value; $(".swap") .each (function (I) {wap_ 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])) }))

twenty-seven。 How to automatically hide or close elements after a period of time (version 1.4 is supported):

/ / this is the way we implemented it using setTimeout in 1.3.2 (function () {$('.mydiv'). Hide ('blind', {}, 5000)); / / and this is the way we can use delay () in 1.4.This is very similar to hibernation) $(".mydiv") .delay (5000) .hide (' blind', {}, 5000).

twenty-eight。 How to dynamically add the created elements to the DOM:

Var newDiv = $(''); newDiv.attr ('id','myNewDiv'). AppendTo (' body')

twenty-nine。 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 the 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 > 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 $('# mytextarea'). MaxLength

thirty。 How to create a basic test for a function

/ / module ("Module B"); test ("some other test", function () {/ / assertion expect (2) indicating how many tests are expected to run inside the module; / / a comparison assertion equivalent to JUnit's assertEquals equals (true, false, "failing test"); equals (true, true, "passing test");})

thirty-one。 How to clone an element in jQuery:

Var cloned = $('# somediv') .clone ()

thirty-two。 How to test whether an element is visible in jQuery

If ($(element) .is (': visible') = = 'true') {/ / the element is visible}

thirty-three。 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 ()) / + $(window). ScrollTop () + 'px'); this.css (' left', ($(window). Width ()-this.width ()) / 2 percent $(window). ScrollLeft () + 'px'); return this } / / use the above function like this: $(element) .center ()

thirty-four。 How to put the values of all elements with a particular name in an array:

Var arrInputValues = new Array (); $("input [name = 'table []']") .each (function () {arrInputValues.push ($(this). Val ());})

thirty-five。 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 ()

thirty-six。 How to use closest to get the parent element:

$('# searchBox'). Closest ('div')

thirty-seven。 How to use Firebug and Firefox to log jQuery events:

/ / 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;}

thirty-eight。 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;})

thirty-nine。 How to force a link to be opened in a new tab:

JQuery ('a.newTab') .live ('click', function () {newwindow=window.open ($(this) .href); jQuery (this). Target = "_ blank"; return false;})

forty。 How to use .siblings () to select peer elements in jQuery

/ / do not do so $('# nav li') .click (function () {$('# nav li'). RemoveClass ('active'); $(this) .addClass (' active');}); / / the alternative is $('# nav li') .click (function () {$(this) .addClass ('active'). Siblings (). RemoveClass (' active');})

forty-one。 How to toggle all check boxes on the page:

Var tog = false; / / or true, if they are selected at load time $('a') .click (function () {$("input [type=checkbox]") .attr ("checked",! tog); tog =! tog;})

forty-two。 How to filter a list of elements based on some input text:

/ / if the value of the element matches the entered text / / the element will be returned $('someClass') .filter (function () {return $(this) .attr ('value') = = $(' input#someId'). Val ();})

forty-three。 How to get the mouse pad cursor positions x and y

$(document) .ready (function () {$(document) .mousemove (function (e) {$('# XY') .html ("X Axis:" + e.pageX + "| Y Axis" + e.pageY);});})

forty-four。 How to make the entire list element (List Element,LI) clickable

$("ul li") .click (function () {_ window.location=$ (this). Find ("a") .attr ("href"); return false;}); Link 1 Link 2 Link 3 Link 4

forty-five。 How to use jQuery to parse XML (basic example):

Function parseXml (xml) {/ / find each Tutorial and print out author $(xml) .find ("Tutorial") .each (function () {$("# output"). Append ($(this) .attr ("author") + ");});}

forty-six。 How to check whether the image has been fully loaded

$('# theImage'). Attr ('src',' image.jpg') .load (function () {alert ('This Image Has Been Loaded');})

forty-seven。 How to use jQuery to specify a namespace for an event:

/ / events can be bound to the namespace $('input') .bind (' blur.validation', function (e) {/ /...}); / / the data method also accepts the namespace $('input') .data (' validation.isValid', true)

forty-eight。 How to check if cookie is enabled

Var dt = new Date (); dt.setSeconds (dt.getSeconds () + 60); [xss_clean] = "cookietest=1; expires=" + dt.toGMTString (); var cookiesEnabled = [xss_clean] .indexOf ("cookietest=")! =-1; if (! cookiesEnabled) {/ / does not enable cookie}

forty-nine。 How to make cookie expire:

Var date = new Date (); date.setTime (date.getTime () + (x * 60 * 1000)); $.cookie ('example',' foo', {expires: date})

fifty。 How to replace any URL on a page with a clickable link

$. Fn.replaceUrl = function () {var regexp = / ((ftp | http | https):\ /\ / (\ winters: {0Power1}\ wicked @)? (\ S+) (: [0-9] +)? (\ / / ([[\ wicked flowers. This.each (function () {$(this). Html ($(this). Html (). Replace (regexp,'$1')); return $(this);} / usage $('p'). ReplaceUrl (); what are the necessary practical jQuery code snippets? have you learned any knowledge or skills? If you want to learn more skills or enrich your knowledge reserve, you are welcome to follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report