jQueryのいくつかの特殊な使い方

13836 ワード

まず、以下のコードは他の人の文章からコピーされたもので、私はいつもどこから検索したのか覚えていません.コードをローカルにコピーしましたが、ローカルファイルが失われるのを恐れて、いっそ自分のブログに書いていつでも参考にしてください.もし原作者が私のコピー行為に不満があれば、私に連絡してください(ここでコメントすればいいです)、私は削除します.
// 1.     jQuery    (    UTF-8   GB2312):
$.ajaxSetup({
    ajaxSettings:{ contentType:"application/x-www-form-urlencoded;chartset=GB2312"} 
});

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

//3. jQuery             
//jQuery event                ,       jQuery      
var $events = $("#foo").data("events");
if( $events && $events["click"] ){   
    //your code 
}

//4.     jQuery      
//            (media-type),   href        。
$('link[media='screen']').attr('href', 'alternative.css');

//5.         (      ):
//                , 
//  jQuery              
//      。        ,
//                  ,
//             。
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.        toggleClass:
//  (toggle)           //             。 //            :
a.hasClass('blueButton') ? a.removeClass('blueButton') : a.addClass('blueButton');
 //toggleClass                    
a.toggleClass('blueButton');

//7.     IE     :
if ($.browser.msie) {// Internet Explorer       }

//8.     jQuery       :
$('#thatdiv').replaceWith('fnuh');

//9.             :
//     
if (! $('#keks').html()) {
    //       ; 
}
//     
if ($('#keks').is(":empty")) {
    //       ; 
}


//10.                       
$("ul > li").click(function () {
  var index = $(this).prevAll().length; //prevAll([expr]):                 
});


//11.            :
//    
$('#foo').click(function(event) { 
  alert('User clicked on "foo."'); 
});
//   ,        
$('#foo').bind('click', {test1:"abc", test2:"123"}, function(event) { 
  alert('User clicked on "foo."' + event.data.test1 + event.data.test2 ); 
}); 

//12.         html    :
$('#lal').append('sometext');

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

//14.              
//                input   ,  
//               
var elements = $('#someid input[type=sometype][value=somevalue]').get(); 

//15.     jQuery      :
jQuery.preloadImages = function() {   for(var i = ; i < arguments.length; i++) { 
    $("<img />").attr('src', arguments[i]); 
  }
}; 
//    
$.preloadImages('image1.gif', '/path/to/image2.png', 'some/image3.jpg'); 

//16.                        :
$('button.someClass').live('click', someFunction); 
//  , jQuery 1.4.2 ,delegate undelegate    
//     live,                 
//  , table  ,      
$("table").each(function(){ 
  $("td", this).live("hover", function(){ 
    $(this).toggleClass("hover"); 
  }); 
}); 
//     
$("table").delegate("td", "hover", function(){ 
  $(this).toggleClass("hover"); 
}); 

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

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

//19.           :
//                 , 
//                 。      , 
//        (:not) (:has) 
//  class “selected”(.selected)    。 
.filter(":not(:has(.selected))")

//20.          :
//   Safari 
(if( $.browser.safari)),  
//   IE6      
(if ($.browser.msie && $.browser.version > 6 )),  
//   IE6      
(if ($.browser.msie && $.browser.version <= 6 )),  
//   FireFox 2      
(if ($.browser.mozilla && $.browser.version >= '1.8' ))

//21.     has()                  :
//jQuery 1.4.*      has     。 
//                                               。 
$("input").has(".email").addClass("email_icon");

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

//23.             
$.expr[':'].mycustomselector = function(element, index, meta, stack){
 // element-   DOM    
 // index –            
 // meta –            
 // stack –             
 //             true  
 //             false 
};  
//         :  
$('.someClasses:test').doSomething(); 

//24.             
if ($('#someDiv').length) {
 //  !!!   ……  
} 

//25.     jQuery                 :
$("#someelement").live('click', function(e) { 
    if( (!$.browser.msie && e.button == ) || ($.browser.msie && e.button == 1) ) { 
        alert("Left Mouse Button Clicked"); 
    } else if(e.button == 2) { 
        alert("Right Mouse Button Clicked"); 
    }
});

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

//27.                   (  1.4  ):
//  1.3.2     setTimeout        
setTimeout(function() { 
    $('.mydiv').hide('blind', {}, 500) 
}, 5000); 
//    1.4     delay()          (      )  
$(".mydiv").delay(5000).hide('blind', {}, 500); 

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

//29.     “Text-Area”        :
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 > 50 || keyCode == 32 || keyCode ==  || keyCode == 13) && !ob.ctrlKey && !ob.altKey && !hasSelection); 
            }; 
            this.onkeyup = function(){ 
                if(this.value.length > max){ 
                    this.value = this.value.substring(,max); 
                } 
            };
        }
    });
};
//    
$('#mytextarea').maxLength(500); 

//30.   jQuery     jQuery    
//jQuery  ajax    ajaxStart,ajaxStop: 
$(document).ajaxStart(function(){
    $("#background,#progressBar").show();
}).ajaxStop(function(){
    $("#background,#progressBar").hide();
});
//ajax        :$.ajax()     global (  : true)        AJAX   .    false         AJAX   ,  ajaxStart   ajaxStop          Ajax   。

//31.    jQuery       :
var cloned = $('#somediv').clone();

//32.  jQuery             
if($(element).is(':visible')) {
   //         
} 

//33.                 :
jQuery.fn.center = function () { 
  return this.each(function(){
    $(this).css({
      position:'absolute',
      top, ( $(window).height() - this.height() ) / 2 + $(window).scrollTop() + 'px', 
      left, ( $(window).width() - this.width() ) / 2 + $(window).scrollLeft() + 'px'     });
  });
}
//          :   
$(element).center(); 

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

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

//36.     closest      :
$('#searchBox').closest('div'); 

//37.     Firebug Firefox   jQuery    :
//          
jQuery.log = jQuery.fn.log = function (msg) {   if (console){ 
    console.log("%s: %o", msg, this); 
  }  return this; 
};//   :  
$('#someDiv').hide().log('div hidden').addClass('someClass');  

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

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

//40.  jQuery     .siblings()       
//       
$('#nav li').click(function(){ 
  $('#nav li').removeClass('active'); 
  $(this).addClass('active'); 
});
//       
$('#nav li').click(function(){ 
  $(this).addClass('active').siblings().removeClass('active'); 
});


//41.              :
var tog = false; 
//    true,                  
$('a').click(function() { 
  $("input[type=checkbox]").attr("checked",!tog); 
  tog = !tog;
});

//42.                    :
//                 ,         
$('.someClass').filter(function() { 
  return $(this).attr('value') == $('input#someId').val(); 
}) 

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

//44.     String     
$.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|
/g, ""); }, trans:function() { return this.replace(/&lt;/g, '<').replace(/&gt;/g,'>').replace(/&quot;/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(1).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+=1) { var ch = this.charAt(i); if (ch!=' '&& ch!="
" && 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) == -1; } }); //45. jQuery : (function($){ $.fn.extend({ pluginOne: function(){ return this.each(function(){ // my code }); }, pluginTwo: function(){ return this.each(function(){ // my code }); } }); })(jQuery); //46. $('#theImage').attr('src', 'image.jpg').load(function() {   alert('This Image Has Been Loaded'); }); //47. jQuery : // $('input').bind('blur.validation', function(e){   // ... }); //data $('input').data('validation.isValid', true); //48. cookie 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 } //49. cookie : var date = new Date(); date.setTime(date.getTime() + (x * 60 * 1000)); $.cookie('example', 'foo', { expires: date }); //50. URL $.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>')     );   }); } //   $('p').replaceUrl();