$.ajaxSetup({ ajaxSettings:{ contentType:"application/x-www-form-urlencoded;chartset=GB2312"} });
<script src="prototype.js"></script> <script src=" http://blogbeta.blueidea.com/jquery.js "></script> <script type="text/javascript"> jQuery.noConflict(); </script>
//JQuery event encapsulation supports judging whether an event is bound to an element. This method is only applicable to jQuery bound events var $events = $("#foo").data("events"); if( $events && $events["click"] ){ //your code }
//Find out the media type you want to switch, and then set the href to the new style sheet. $('link[media='screen']').attr('href', 'alternative.css');
// As far as possible, use the tag name as the prefix of the class name, // In this way, jQuery does not need to spend more time searching // The element you want. One more thing to remember is that, // The more specific the operation of the elements on your page, // The less time it takes to execute and search. 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>
// Toggle class allows you to // Whether it exists to add or delete this class. // In this case, some developers use: a.hasClass( ' blueButton ' ) ? a.removeClass( ' blueButton ' ) : a.addClass( ' blueButton ' ); // ToggleClass allows you to do this easily by using the following statement a.toggleClass( ' blueButton ' );
if ($.browser.msie) { // Internet Explorer is a sadist }
$( ' #thatdiv ' ).replaceWith( ' fnuh ' );
// Method 1 if ($( ' #keks ' ).html()) { // Nothing was found; } // Method 2 if ($( ' #keks ' ).is( " :emty " )) { // Nothing was found; }
$( " ul > li " ).click( function () { var index = $( this ).prevAll().length; // PrevAll ([expr]): Find all the peer elements before the current element });
// Method 1 $( ' #foo ' ).click( function (event) { alert( ' User clicked on "foo. " ' ); }); // Method 2: Support dynamic parameter transfer $( ' #foo ' ).bind( ' click ' , {test1: " abc " , test2: " one hundred and twenty-three " }, function (event) { alert( ' User clicked on "foo. " ' + event.data.test1 + event.data.test2 ); });
$( ' #lal ' ).append( ' sometext ' );
var e = $( "" , { href: " # " , class: " a-class another-class " , title: " ... " });
// When using many similar input elements with different types, // This accuracy based approach is useful var elements = $( ' #someid input[type=sometype][value=somevalue] ' ).get();
jQuery.preloadImages = function () { for ( var i = ; i < arguments.length; i ++ ) { $( " <img /> " ).attr( ' src ' , arguments[i]); } }; // usage $.preloadImages( ' image1.gif ' , ' /path/to/image2.png ' , ' some/image3.jpg ' );
$( ' button.someClass ' ).live( ' click ' , someFunction); // Note that in jQuery 1.4.2, the delegate and undelete options // They are introduced instead of live because they provide better context support // For example, for table, you used to use $( " table " ).each( function (){ $( " td " , this ).live( " hover " , function (){ $( this ).toggleClass( " hover " ); }); }); // Now use $( " table " ).delegate( " td " , " hover " , function (){ $( this ).toggleClass( " hover " ); });
$( ' #someElement ' ).find( ' option:selected ' );
$( " p.value:contains('thetextvalue') " ).hide();
// Allows you to reduce the filter of matching elements in the collection, // Only those parts that match the given selector are left. under these circumstances, // Query deletes any (: not) Yes (: has) // Contains child nodes whose class is "selected" (. selected). .filter( " :not(:has(.selected)) " )
// JQuery 1.4. * includes support for this has method. // This method finds out whether an element contains another element class or any other thing you are looking for and want to operate on. $( " input " ).has( " .email " ).addClass( " email_icon " );
$(document).bind( ' contextmenu ' , function (e){ return false ; });
$.expr[ ' : ' ].mycustomselector = function (element, index, meta, stack){ // Element - a DOM element // Index – The current circular index in the stack // Meta – Metadata about selectors // Stack – stack of all elements to loop // Returns true if the current element is included // If it does not contain the current element, it returns false}; // Custom selector usage: $( ' .someClasses:test ' ).doSomething();
if ($( ' #someDiv ' ).length) { // hooray!!! It exists }
$( " #someelement " ).live( ' click ' , function (e) { if ( ( ! $.browser.msie && e.button == ) || ($.browser.msie && e.button == one ) ) { alert( " Left Mouse Button Clicked " ); } else if (e.button == two ) { alert( " Right Mouse Button Clicked " ); } });
var el = $( ' #id ' ); el.html(el.html().replace( / word / ig, '' ));
// This is the way we use setTimeout in 1.3.2 setTimeout( function () { $( ' .mydiv ' ).hide( ' blind ' , {}, five hundred ) }, five thousand ); // This is the way that you can use the function delay() in 1.4 (this is much like sleeping) $( " .mydiv " ).delay( five thousand ).hide( ' blind ' , {}, five hundred );
var newDiv = $( ' <div></div> ' ); newDiv.attr( ' id ' , ' myNewDiv ' ).appendTo( ' body ' );
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; } 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 > : this .selectionStart != this .selectionEnd; return ! ( this .value.length >= max && (keyCode > fifty || keyCode == thirty-two || keyCode == || keyCode == thirteen ) && ! ob.ctrlKey && ! ob.altKey && ! hasSelection); }; this .onkeyup = function (){ if ( this .value.length > max){ this .value = this .value.substring( ,max); } }; } }); }; // usage $( ' #mytextarea ' ).maxLength( five hundred );
// JQuery registers the ajax global event ajaxStart, ajaxStop: $(document).ajaxStart( function (){ $( " #background,#progressBar " ).show(); }).ajaxStop( function (){ $( " #background,#progressBar " ).hide(); }); // Disable global events for ajax requests: $. ajax() has a parameter global (default: true) whether to trigger global Ajax events. If set to false, global Ajax events will not be triggered. For example, ajaxStart or ajaxStop can be used to control different Ajax events.
var cloned = $( ' #somediv ' ).clone();
if ($(element).is( ' :visible ' )) { // The element is visible }
jQuery.fn.center = function () { return this .each( function (){ $( this ).css({ position: ' absolute ' , top, ( $(window).height() - this .height() ) / two + $(window).scrollTop() + ' px ' , left, ( $(window).width() - this .width() ) / two + $(window).scrollLeft() + ' px ' }); }); } // Use the above function: $(element).center();
var arrInputValues = new Array(); $( " input[name='xxx'] " ).each( function (){ arrInputValues.push($( this ).val()); });
( function ($) { $.fn.stripHtml = function () { var regexp = / <("[^"]*"|'[^']*'|[^'">])*> / gi; this .each( function () { $( this ).html( $( this ).html().replace(regexp, '' ) ); }); return $( this ); } })(jQuery); // Usage: $( ' p ' ).stripHtml();
$( ' #searchBox ' ).closest( ' div ' );
// Allow chained logging jQuery.log = jQuery.fn.log = function (msg) { if (console){ console.log( " %s: %o " , msg, this ); } return this ; }; // Usage: $( ' #someDiv ' ).hide().log( ' div hidden ' ).addClass( ' someClass ' );
$( ' a.popup ' ).live( ' click ' , function (){ var newwindow = window.open($( this ).attr( ' href ' ), '' , ' height=200,width=150 ' ); if (window.focus) { newwindow.focus(); } return false ; });
$( ' a.newTab ' ).live( ' click ' , function (){ var newwindow = window.open( this .href); $( this ).target = " _blank " ; return false ; });
// No $( ' #nav li ' ).click( function (){ $( ' #nav li ' ).removeClass( ' active ' ); $( this ).addClass( ' active ' ); }); // The alternative is $( ' #nav li ' ).click( function (){ $( this ).addClass( ' active ' ).siblings().removeClass( ' active ' ); });
var tog = false ; // Or true, if they are selected when loading $( ' a ' ).click( function () { $( " input[type=checkbox] " ).attr( " checked " , ! tog); tog = ! tog; });
// 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(); })
$(document).ready( function () { $(document).mousemove( function (e){ $(’#XY’).html(”X Axis : ” + e.pageX + ” | Y Axis ” + e.pageY); }); });
$.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 (){ return this .replace( / (^\s*)|(\s*$)|\r|\n / g, "" ); }, trans: function () { return this .replace( / < / g, ' < ' ).replace( / > / g, ' > ' ).replace( / " / g, ' " ' ); }, replaceAll: function (os, ns) { return this .replace( new RegExp(os, " gm " ),ns); }, skipChar: function (ch) { if ( ! this || this .length === ) { return '' ;} if ( this .charAt( ) === ch) { return this .substring( one ).skipChar(ch);} return this ; }, 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 = ; i < this .length; i += one ) { var ch = this .charAt(i); if (ch != ' ' && ch != " \n " && ch != " \t " && ch != " \r " ) { return false ;} } return true ; }, 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 (){ return this .isUrl() && this .indexOf( " :// " + document.domain) == - one ; } });
( function ($){ $.fn.extend({ pluginOne: function (){ return this .each( function (){ // my code }); }, pluginTwo: function (){ return this .each( function (){ // my code }); } }); })(jQuery);
$( ' #theImage ' ).attr( ' src ' , ' image.jpg ' ).load( function () { alert( ' This Image Has Been Loaded ' ); });
// Events can bind namespaces like this $( ' input ' ).bind( ' blur.validation ' , function (e){ // ... }); // The data method also accepts namespaces $( ' input ' ).data( ' validation.isValid ' , true );
var dt = new Date(); dt.setSeconds(dt.getSeconds() + sixty ); document.cookie = " cookietest=1; expires= " + dt.toGMTString(); var cookiesEnabled = document.cookie.indexOf( " cookietest= " ) != - one ; if ( ! cookiesEnabled) { // Cookies are not enabled }
var date = new Date(); date.setTime(date.getTime() + (x * sixty * one thousand )); $.cookie( ' example ' , ' foo ' , { expires: date });
$.fn.replaceUrl = function () { var regexp = / ((ftp|http|https):\/\/(\w+:{0,1}\w*@)? (\S+)(:[0-9]+)? (\/|\/([\w#!:.?+=&%@!\-\/]))?) / gi; return this .each( function () { $( this ).html( $( this ).html().replace(regexp, ' <a href="$1">$1</a>') ); }); } //Usage $( ' p ' ).replaceUrl();