50 more practical jQuery code snippets _ jquery

Source: Internet
Author: User
This article will show you 50 jquery code snippets that can help your javascript project. Some of the code snippets are supported from jQuery1.4.2, others are actually useful functions or methods that can help you complete things quickly and well. These are code segments with the best performance I can remember. If you find anything better, paste your version in the comments! I hope you can find something helpful in this article.

1. How to Create nested filters:

// Allows you to reduce the filter of matching elements in the Set, // only the part that matches the given selector is left. In this case, // the query deletes any subnodes without (: not) (: has) // containing the class "selected" (. selected .. Filter (": not (: has (. selected ))")

2. How to reuse element search

Var allItems = $ ("p. item "); var keepList = $ (" p # container1 p. item "); // now you can continue to work with these jQuery objects. For example, // crop the "keep list" based on the check box. The name of the check box // conforms to <DIV> class names: $ (formToLookAt + "input: checked "). each (function () {keepList = keepList. filter (". "+ $ (this ). attr ("name") ;}); </DIV>

3. Any use of has () to check whether an element contains a class or element:

// JQuery. * contains support for this has method. This method finds out whether/or not an element contains another element class or any other things that you are looking for and operating on. $ ("Input"). has (". email"). addClass ("email_icon ");

4. How to Use jQuery to switch between style sheets

// Find the media type you want to switch to, and then set href to a new style sheet. $ ('Link [media = 'screen'] '). attr ('href', 'Alternative.css ');

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

// Use the label name as the prefix of the class name as much as possible. // jQuery does not need to spend more time searching for the elements you want. Remember that the more specific the operations on 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 correctly use ToggleClass:

// Toggle class allows you to add or delete a Class Based on the existence or absence of a class. // In this case, some developers use: a. hasClass ('bluebutton ')? A. removeClass ('bluebutton '):. addClass ('bluebutton '); // toggleClass allows you to use the following statements to easily do this.. toggleClass ('bluebutton ');

7. How to set the unique features of IE:

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

8. How to Use jQuery to replace an element:

$('#thatp').replaceWith('fnuh');

9. How to verify whether an element is null:

If ({('{keks'}.html () = null) {// nothing found ;}

10. How to Find the index number of an element from an unsorted set

$("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."');});

12. How to append or add html to an element:

$('#lal').append('sometext');

13. How to Use literal to define attributes when creating elements

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

14. How to use multiple attributes for filtering

// When many similar input elements have different types, // This precision-based method is useful var elements = $ ('# someid input [type = sometype] [value = somevalue]'). get ();

15. How to Use jQuery to pre-load images:

JQuery. preloadImages = function () {for (var I = 0; I <arguments. length; I ++) {$ (""). attr ('src', arguments [I]) ;}}; // usage example .preloadimages('image1.gif ','/path/to/image2.png ', 'some/image3.jpg ');

16. How to Set Event Handlers 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, for table, you used to use //. live () $ ("table "). each (function () {$ ("td", this ). live ("hover", function () {$ (this ). toggleClass ("hover") ;}); // $ ("table") is used now "). delegate ("td", "hover", function () {$ (this ). toggleClass ("hover ");});

17. How to find a selected option element:

$('#someElement').find('option:selected');

18. How to hide an element that contains a value text:

$("p.value:contains('thetextvalue')").hide();

19. How to automatically scroll to a certain 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. $ ('. Area_name'). autoscroll ();

20. How to detect various browsers:

Detect Safari (if ($. browser. (if ($. browser. msie & $. browser. version> 6) to check IE6 and earlier versions (if ($. browser. msie & $. browser. version <= 6) to detect FireFox 2 and later versions (if ($. browser. mozilla & $. browser. version> = '1. 8 '))

21. How to replace words in a string

var el = $('#id');  el.html(el.html().replace(/word/ig, ''));
22. How to disable context menu by right-clicking:
$(document).bind('contextmenu',function(e){  return false;});

23. How to define a custom Selector

$. Expr [':']. mycustomselector = function (element, index, meta, stack) {// element-a DOM element // index-the current cyclic index in the stack // meta-metadata about the selector // stack-stack of all elements to be recycled // if it contains returns true if the current element is not included. // returns false if the current element is not included }; // custom selector usage: $ ('. 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 two situations: Right-click and left-click:

$("#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 retain a value in the text input field when the user does not enter a value. // a default value of wap_val = []; $ (". 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]) ;}}) ;});
 

27. How to automatically hide or disable elements after a period of time (version 1.4 is supported ):

// This is the setTimeout (function () {$ ('. myp '). hide ('blind', {}, 500)}, 5000); // while this is in 1.4, you can use delay () implementation of this function (this is like sleep) $ (". myp "). delay( 5000 ). hide ('blind', {}, 500 );

28. How to dynamically Add the created elements 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 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 (0, max) ;}}}}) ;}; // usage $ ('# mytextarea '). maxLength (1, 500 );

30. How to create a basic test for a function

// Separate the test into the module Module ("module B"); test ("some other test", function () {// specify the number of assertEquals (2) that are expected to run in the test; // A comparison asserted, equivalent to assertEquals (true, false, "failing test") of JUnit "); equals (true, true, "passing test ");});

31. In jQuery, how can I get an element:

var cloned = $('#somep').clone();

32. How to test whether an element is visible in jQuery?

If ($ (element). is (': visible') = 'true') {// This 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;} // use the above function: $ (element ). center ();

34. How to put the values of all elements with a specific name in an array:

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

35. How to remove html from elements

(Function ($) {$. fn. stripHtml = function () {var regexp =/<("[^"] * "| '[^'] * '| [^'">]) *>/gi; this. each (function () {publish (this).html (). replace (regexp, "") ;}); return $ (this) ;}} (jQuery); // usage: $ ('P '). stripHtml ();

36. How to Use closest to obtain the parent element:

$('#searchBox').closest('p');

37. How to Use Firebug and Firefox to record jQuery Event Logs:

// Enable chained logging // usage: $ ('# somediv '). hide (). log ('P den '). addClass ('someclass '); jQuery. log = jQuery. fn. log = function (msg) {if (console) {console. log ("% s: % o", msg, this) ;}return this ;};

38. How to force the link to be opened in the 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 peer Elements

// Do not do this $ ('# nav li '). click (function () {$ ('# nav li '). removeClass ('active'); $ (this ). addClass ('active') ;}); // the alternative method is $ ('# nav li '). click (function () {$ (this ). addClass ('active '). siblings (). removeClass ('active ');});

41. How to switch all check boxes on the page:

Var tog = false; // or true. If they are selected during loading, $ ('A '). click (function () {$ ("input [type = checkbox]"). attr ("checked ",! Tog); tog =! Tog ;});

42. How to filter an element list based on some input text:

// If the element value matches the input text, // The element will be returned $ ('. someClass '). filter (function () {return $ (this ). attr ('value') =$ ('input # someid '). val ();})

43. How to obtain the mouse pad position x and y

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

44. How to change the entire List Element (LI) to clickable

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

45. How to Use jQuery to parse XML (basic example ):

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

46. How to check whether the image has been fully loaded

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

47. 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 namespace $ ('input '). data ('validation. isvalid', true );

48. How to check whether cookies are enabled

Var dt = new Date (); dt. setSeconds (dt. getSeconds () + 60); document. cookie = "cookietest = 1; expires =" + dt. toGMTString (); var cookiesEnabled = document. cookie. indexOf ("cookietest = ")! =-1; if (! CookiesEnabled) {// cookie not enabled}

49. How to Make the cookie expire:

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

50. How to use a clickable link to replace any URL on the page

$. Fn. replaceUrl = function () {var regexp =/(ftp | http | https): \/(\ w +: {0, 1} \ w *@)? (\ S +) (: [0-9] + )? (\/| \/([\ W #! :.? + = & % @! \-\/])?) /Gi; this. each (function () {publish (this).html (). replace (regexp, '$ 1') ;}); return $ (this) ;}// usage $ ('P '). replaceUrl ();

Just sort it out.

If you are not familiar with it, I suggest you read the ultra-practical jquery code segment. The script home has a pdf version. Let's take a look.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.