JQuery經常使用的代碼片斷

JQuery經常使用的代碼片斷 JQuery在當前衆多網站開發中都有用到。他簡易的操做以及對各個瀏覽器的兼容性,被廣大的開發者一致看好。 下面是一些經常使用實用的 JQuery 代碼片斷。看看有沒有須要收藏的吧:javascript

1. 阻止連接點擊

$("a").on("click", function(e){
  e.preventDefault();
});

2. 幻燈片切入

// Fade
$( 「.btn" ).click(function() {
$( 「.element" ).fadeToggle("slow");
});

// Toggle
$( 「.btn" ).click(function() {
$( 「.element" ).slideToggle("slow");
});

當咱們須要在當前一面加載一個div或其餘標籤的時候十分有效。css

3.加載鼠標懸停樣式 class

$('.btn').hover(function(){
    $(this).addClass(‘hover’);
}, function(){
    $(this).removeClass(‘hover’);
});

4.模塊點擊。

$(".myBox").click(function(){
     window.location=$(this).find("a").attr("href"); 
     return false;
});

5. 檢查圖像是否加載完成

$(‘img’).load(function() {
console.log(‘image load successful’);
});

6.回到頂部html

// Back To Top
$('a.top').click(function(){
    $(document.body).animate({scrollTop : 0},800);
        return false;
});

//Create an anchor tag
<a class="top" href="#">Back to top</a>

7.加載外部頁面

$("#content").load("somefile.html", function(response, status, xhr) {
  // error handling
  if(status == "error") {
    $("#content").html("An error occured: " + xhr.status + " " + xhr.statusText);
  }
});

8. 彈窗

jQuery('a.popup').live('click', function() {</pre>
 newwindow=window.open($(this).attr('href'),'','height=100,width=100');
  if(window.focus) {newwindow.focus()}
  return false;
 });

9. 未成功加載圖片,顯示默認

$('img').error(function(){
    $(this).attr('src', ‘img/broken.png’);
});

10.刷新內置頁面

$('iframe').attr('src', $('iframe').attr('src'));

11. 鍵盤事件監聽

$('input').keydown(function(e) {
  // variable e contains keystroke data
  // only accessible with .keydown()
  if(e.which == 11) {
     e.preventDefault();
  }
});

$('input').keyup(function(event) {
  // run other event codes here         
});

12.密碼強度驗證

$('#pass').keyup(function(e) {
     var strongRegex = new RegExp("^(?=.{8,})(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*\\W).*$", "g");
     var mediumRegex = new RegExp("^(?=.{7,})(((?=.*[A-Z])(?=.*[a-z]))|((?=.*[A-Z])(?=.*[0-9]))|((?=.*[a-z])(?=.*[0-9]))).*$", "g");
     var enoughRegex = new RegExp("(?=.{6,}).*", "g");
     if (false == enoughRegex.test($(this).val())) {
             $('#passstrength').html('More Characters');
     } else if (strongRegex.test($(this).val())) {
             $('#passstrength').className = 'ok';
             $('#passstrength').html('Strong!');
     } else if (mediumRegex.test($(this).val())) {
             $('#passstrength').className = 'alert';
             $('#passstrength').html('Medium!');
     } else {
             $('#passstrength').className = 'error';
             $('#passstrength').html('Weak!');
     }
     return true;
});

13.禁止/容許輸入

$('input[type="submit"]').attr("disabled", true);
$('input[type="submit"]').removeAttr("disabled");

14.遍歷 DOM

$("div#home").prev("div"); //取得包含匹配的元素集合中每個元素緊鄰的前一個同輩元素的元素集合。
$("div#home").next("ul"); //  取得匹配的元素集合中每個元素緊鄰的後面同輩元素的元素集合
$("div#home").parent(); // 取得匹配元素集合中,每一個元素的父元素。
$("div#home").children("p"); //得到匹配元素集合中每一個元素的子元素

15.刷新部分頁面內容

setInterval(function() { 
$("#class-id").load(location.href+" #class-id>*",""); 
}, 2000); // seconds to wait

16.增長元素

var sometext = "Say something awesome";
$("p#sample1").append(sometext); // added after
$("p#tsample1").prepend(sometext); // added before

17.新窗口打開外部連接

$('a').each(function() {
    var a = new RegExp('/' + [removed].host + '/');
if(!a.test(this.href)) {
    $(this).click(function(event) {
        event.preventDefault();
        event.stopPropagation();
        window.open(this.href, '_blank');
    });
    }
});

18.檢查輸入框,開啓按鈕可用

$('#username').keyup(function() {
    $('#submit').attr('disabled', !$('#username').val());
});

19.jQuery Cookies set/get/delete

//get cookie
function getCookie( name ) {   
    var start = document.cookie.indexOf( name + "=" );
    var len = start + name.length + 1;
    if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) ) {
        return null;
    }
    if ( start == -1 ) return null;
    var end = document.cookie.indexOf( ';', len );
    if ( end == -1 ) end = document.cookie.length;
    return unescape( document.cookie.substring( len, end ) );
}

//set cookie
function setCookie( name, value, expires, path, domain, secure ) {
    var today = new Date();
    today.setTime( today.getTime() );
    if ( expires ) {
        expires = expires * 1000 * 60 * 60 * 24;
    }
    var expires_date = new Date( today.getTime() + (expires) );
    document.cookie = name+'='+escape( value ) +
        ( ( expires ) ? ';expires='+expires_date.toGMTString() : '' ) + //expires.toGMTString()
        ( ( path ) ? ';path=' + path : '' ) + 
        ( ( domain ) ? ';domain=' + domain : '' ) +
        ( ( secure ) ? ';secure' : '' );
}

//delete cookie
function deleteCookie( name, path, domain ) {
    if ( getCookie( name ) ) document.cookie = name + '=' +
            ( ( path ) ? ';path=' + path : '') +
            ( ( domain ) ? ';domain=' + domain : '' ) +
            ';expires=Thu, 01-Jan-1970 00:00:01 GMT';
}

20.所有選中/不選

<!-- jQuery -->
$('.SelectAll').live('click', function(){
$(this).closest('.divAll').find('input[type=checkbox]').attr('checked', true);
return false; });
$('.DeselectAll').live('click', function(){
$(this).closest('.divAll').find('input[type=checkbox]').attr('checked', false);
return false; });
<!-- HTML -->
<div class="divAll">  <a href="#" class="SelectAll">Select All</a>  
<a href="#" class="DeselectAll">Deselect All</a>  <br />  \
<input type="checkbox" /><label for="Lahore">Lahore</label> 
<input type="checkbox" /><label for="Karachi">Karachi</label> 
<input type="checkbox" /><label for="Islamabad">Islamabad</label> </div>

21.TextArea長度限制

<!-- jQuery -->
   var MaxLength = 500;
       $('#txtDescription').keypress(function(e)
       {
          if ($(this).val().length >= MaxLength) {
          e.preventDefault();}
       });
<!-- HTML -->
<asp:TextBox runat="server" TextMode="MultiLine" Columns="50" Rows="5"></asp:TextBox>

22.調整圖片大小

(function($) {
    $.fn.imageResize = function(options) {

        var that = this;
        var settings = {
            width: 150,
            height: 150
        };
        options = $.extend(settings, options);

        if (!that.is('img')) {
            return;
        }

        return that.each(function() {

            var maxWidth = options.width;
            var maxHeight = options.height;
            var ratio = 0;
            var width = $(that).width();
            var height = $(that).height();

            if (width > maxWidth) {
                ratio = maxWidth / width;
                $(that).css('width', maxWidth);
                $(that).css('height', height * ratio);

            }

            if (height > maxHeight) {
                ratio = maxHeight / height;
                $(that).css('height', maxHeight);
                $(that).css('width', width * ratio);

            }

        });

    };
})(jQuery);

23.驗證的電子郵件地址

<!-- jQuery -->
$('#txtEmail').blur(function(e) {
            var sEmail = $('#txtEmail').val();
            if ($.trim(sEmail).length == 0) {
                alert('Please enter valid email address');
                e.preventDefault();
            }       
            var filter = /^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]
                             {2,4}|[0-9]{1,3})(\]?)$/;       
            if (filter.test(sEmail)) {
                alert('Valid Email');
            }
            else {
                alert('Invalid Email');
                e.preventDefault();
            }
        });
<!-- HTML -->
<asp:TextBox runat="server" />

24.文本輸入框臨時信息

<!-- jQuery -->
$('input[type=text]').focus(function(){   
           var $this = $(this);
           var title = $this.attr('title');
           if($this.val() == title)
           {
               $this.val('');
           }
}).blur(function() {
           var $this = $(this);
           var title = $this.attr('title');
           if($this.val() == '')
           {
               $this.val(title);
           }
});
<!-- HTML -->
<div>
       <input type="text" 
       name="searchCompanyName" 
       value="Company Name"
       title="Company Name" />
</div>

結束

以上就是一些常常用到的代碼片斷了。因爲常用。不妨收藏一下java

相關文章
相關標籤/搜索