50 jquery code snippets) and 50 jquery code snippets

Source: Internet
Author: User

50 jquery code snippets (for conversion) and 50 jquery code snippets

This article will show you 50 jquery code snippets that can help your javascript project. Some of the code segments are supported since jQuery1.4.2, while others are actually useful functions or methods. They can help you complete things quickly and well. If you find anything you can do better, paste your version in the comments!

1. How to modify jQuery default encoding (for example, change the default UTF-8 to GB2312 ):

$.ajaxSetup({
ajaxSettings:{ contentType:"application/x-www-form-urlencoded; charset=GB2312"}
});


2. Solve the Problem of coexistence of jQuery and prototype and $ global variable conflict:

<script src="prototype.js"></script>
<script src="http://blogbeta.blueidea.com/jquery.js"></script>
<script type="text/javascript">
jQuery.noConflict();
</script>

Note: you must first introduce prototype. js and then jquery. js. The sequence is not wrong.

3. jQuery checks whether an event is bound to an element.

// JQuery event encapsulation supports determining whether events are bound to an element. This method is only applicable to events bound to jQuery.
Var $ events = $ ("# foo"). data ("events ");
If ($ events & $ events ["click"]) {
// Your code
}


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 class name prefix whenever possible,
// JQuery does not need to spend more time searching.
// The elements you want. Remember that,
// The more specific the operations on the elements on your page,
// The lower the execution and search time.
Var in_stock = $ ('# shopping_cart_items input. is_in_stock ');

<Ul id = "shopping_cart_items">
<Li> <input type = "radio" value = "Item-X" name = "item" class = "is_in_stock"/> Item X </li>
<Li> <input type = "radio" value = "Item-Y" name = "item" class = "3-5_days"/> Item Y </li>
<Li> <input type = "radio" value = "Item-Z" name = "item" class = "unknown"/> Item Z </li>
</Ul>


6. How to correctly use toggleClass:

// Toggle class allows you
// Whether the class exists to be added or deleted.
// In this case, some developers use:
A. hasClass ('bluebutton ')? A. removeClass ('bluebutton'): a. addClass ('bluebutton ');
// ToggleClass allows you to use the following statements to easily achieve this
A. 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:

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


9. How to verify whether an element is null:

// Method 1
If (! Certificate ('{keks'}.html ()){
// Nothing is found;
}

// Method 2
If ($ ('# keks'). is (": empty ")){
// Nothing is found;
}


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

$ ("Ul> li"). click (function (){
Var index = $ (this). prevAll (). length; // prevAll ([expr]): Find all peer elements before the current element
});


11. How to bind a function to an event:

// Method 1
$ ('# Foo'). click (function (event ){
Alert ('user clicked on "foo ."');
});

// Method 2: Support for dynamic parameter passing
$ ('# Foo'). bind ('click', {test1: "abc", test2: "123"}, function (event ){
Alert ('user clicked on "foo." '+ event. data. test1 + event. data. test2 );
});


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 very 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 ++ ){
$ ("}
};
// Usage
Pai.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: In jQuery 1.4.2, the delegate and undelegate options
// Be introduced to replace live because they provide better context support
// For example, in table, you used
$ ("Table"). each (function (){
$ ("Td", this). live ("hover", function (){
$ (This). toggleClass ("hover ");
});
});
// Used now
$ ("Table"). 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 Create nested filters:

// Allows you to reduce the filter of matching elements in the set,
// Only the parts that match the given selector are left. In this case,
// The query has deleted any (: not) with (: has)
// Contains child nodes whose class is "selected" (. selected.
. Filter (": not (: has (. selected ))")


20. How to detect various browsers:

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

 

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

// JQuery. * contains support for this has method.
// This method is used to find out whether an element contains another element class or any other stuff you are looking for and operating on.
$ ("Input"). has (". email"). addClass ("email_icon ");


22. How to disable context menu by right-clicking:

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


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
// Returns true if it contains the current element.
// If the current element is not included, false is returned };
// 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");
} elseif(e.button ==2) {
alert("Right Mouse Button Clicked");
}
});


26. How to replace words in a string

var el = $('#id'); 
el.html(el.html().replace(/word/ig, ''));


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

// This is implemented using setTimeout in 1.3.2.
SetTimeout (function (){
$ ('. Mydiv'). hide ('blind', {}, 500)
},5000 );
// This method can be implemented using the delay () function in 1.4 (this is like sleep)
$ (". Mydiv"). delay (5000). hide ('blind', {}, 500 );


28. How to dynamically Add the created elements to the DOM:

var newDiv = $('<div></div>'); 
newDiv.attr('id','myNewDiv').appendTo('body');


29. How to limit the number of characters in the Text-Area field:

JQuery. fn. maxLength = function (max ){
Return 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;
} Elseif (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 (500 );


30. How to register and disable jQuery global events

// JQuery registers the ajax global event ajaxStart and ajaxStop:
$ (Document). ajaxStart (function (){
$ ("# Background, # progressBar"). show ();
}). AjaxStop (function (){
$ ("# Background, # progressBar"). hide ();
});
// Disable global events for ajax requests: $. ajax () has a global parameter (default: true) to determine whether to trigger a global AJAX event. setting false does not trigger global AJAX events. For example, ajaxStart or ajaxStop can be used to control different Ajax events.


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

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


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

If ($ (element). is (': visible ')){
// This element is visible.
}


33. How to place an element in the center of the screen:

JQuery. fn. center = function (){
Returnthis. each (function (){
Certificate (this).css ({
Position: 'absolute ',
Top, ($ (window). height ()-this. height ()/2 + $ (window). scrollTop () + 'px ',
Left, ($ (window). width ()-this. width ()/2 + $ (window). scrollLeft () + 'px'
});
});
}
// Use the above function in this way:
$ (Element). center ();

 

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

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


35. How to remove HTML from elements

(Function ($ ){
$. Fn. stripHtml = function (){
Var regexp =/<("[^"] * "| '[^'] * '| [^'">]) *>/gi;
This. each (function (){
Certificate (this).html (certificate (this).html (). replace (regexp ,''));
});
Return $ (this );
}
}) (JQuery );
// Usage:
$ ('P'). stripHtml ();


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

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


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

// Enable chained Logging
JQuery. log = jQuery. fn. log = function (msg ){
If (console ){
Console. log ("% s: % o", msg, this );
}
Returnthis;
};
// Usage:
$ ('# Somediv'). hide (). log ('div den'). addClass ('someclass ');


38. How to force the link to be opened in the pop-up window:

$('a.popup').live('click', function(){ 
  var newwindow = window.open($(this).attr('href'),'','height=200,width=150');
  if (window.focus) {
    newwindow.focus();
  }
  returnfalse;
});


39. How to force the link to open in a new tab:

$('a.newTab').live('click', function(){ 
  var newwindow=window.open(this.href);
  $(this).target ="_blank";
  returnfalse;
});


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 extend the String object

$.extend(String.prototype, {
isPositiveInteger:function(){
return (new RegExp(/^[1-9]\d*$/).test(this));
},
isInteger:function(){
return (new RegExp(/^\d+$/).test(this));
},
isNumber: function(value, element) {
return (new RegExp(/^-?(?:\d+|\d{1,3}(?:,\d{3})+)(?:\.\d+)?$/).test(this));
},
trim:function(){
returnthis.replace(/(^\s*)|(\s*$)|\r|\n/g, "");
},
trans:function() {
returnthis.replace(/&lt;/g, '<').replace(/&gt;/g,'>').replace(/&quot;/g, '"');
},
replaceAll:function(os, ns) {
returnthis.replace(new RegExp(os,"gm"),ns);
},
skipChar:function(ch) {
if (!this||this.length===0) {return'';}
if (this.charAt(0)===ch) {returnthis.substring(1).skipChar(ch);}
returnthis;
},
isValidPwd:function() {
return (new RegExp(/^([_]|[a-zA-Z0-9]){6,32}$/).test(this));
},
isValidMail:function(){
return(new RegExp(/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/).test(this.trim()));
},
isSpaces:function() {
for(var i=0; i<this.length; i+=1) {
var ch =this.charAt(i);
if (ch!=''&& ch!="\n"&& ch!="\t"&& ch!="\r") {returnfalse;}
}
returntrue;
},
isPhone:function() {
return (new RegExp(/(^([0-9]{3,4}[-])?\d{3,8}(-\d{1,6})?$)|(^\([0-9]{3,4}\)\d{3,8}(\(\d{1,6}\))?$)|(^\d{3,8}$)/).test(this));
},
isUrl:function(){
return (new RegExp(/^[a-zA-z]+:\/\/([a-zA-Z0-9\-\.]+)([-\w .\/?%&=:]*)$/).test(this));
},
isExternalUrl:function(){
returnthis.isUrl() &&this.indexOf("://"+document.domain) ==-1;
}
});


45. How to standardize writing jQuery plug-ins:

(function($){
$.fn.extend({
pluginOne: function(){
returnthis.each(function(){
// my code
});
},
pluginTwo: function(){
returnthis.each(function(){
// my code
});
}
});
})(jQuery);


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 namespaces in this way
$ ('Input'). bind ('blur. valider', 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 () + 60 );
Document. cookie = "cookietest = 1; expires =" + dt. toGMTString ();
Var cookiesEnabled = document. cookie. indexOf ("cookietest = ")! =-1;
If (! CookiesEnabled ){
// No cookie is 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;
Return this. each (function (){
Certificate (this).html (
Parameters (this).html (). replace (regexp, '<a href = "$1"> $1 </a> ')
);
});
}
// Usage
$ ('P'). replaceUrl ();

 


JQuery code ??

The key is to convert the string obtained with .html () to a number.

There are three methods to convert a string to a number in js:
1. conversion functions
Var num = parseInt ($ ("# speed" ).html (); // convert to an integer
2. Forced conversion
Var num = Number ($ ("# speed" into .html (); // It converts the entire value, not the partial value.
3. Weak type conversion of js
Var num = $ ("# speed" ).html (); // when compared with a number, it can also be used as a number, but this method is not recommended.

Hope to help you!

How to convert jquery's code to js,

Var id = document. getElementById ("Code"). value;

Var cid = document. getElementById ("Id"). value;
Id = id + cid

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.