JQuery經常使用的代碼片斷 JQuery在當前衆多網站開發中都有用到。他簡易的操做以及對各個瀏覽器的兼容性,被廣大的開發者一致看好。 下面是一些經常使用實用的 JQuery 代碼片斷。看看有沒有須要收藏的吧:javascript
$("a").on("click", function(e){ e.preventDefault(); });
// Fade $( 「.btn" ).click(function() { $( 「.element" ).fadeToggle("slow"); }); // Toggle $( 「.btn" ).click(function() { $( 「.element" ).slideToggle("slow"); });
當咱們須要在當前一面加載一個div或其餘標籤的時候十分有效。css
$('.btn').hover(function(){ $(this).addClass(‘hover’); }, function(){ $(this).removeClass(‘hover’); });
$(".myBox").click(function(){ window.location=$(this).find("a").attr("href"); return false; });
$(‘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>
$("#content").load("somefile.html", function(response, status, xhr) { // error handling if(status == "error") { $("#content").html("An error occured: " + xhr.status + " " + xhr.statusText); } });
jQuery('a.popup').live('click', function() {</pre> newwindow=window.open($(this).attr('href'),'','height=100,width=100'); if(window.focus) {newwindow.focus()} return false; });
$('img').error(function(){ $(this).attr('src', ‘img/broken.png’); });
$('iframe').attr('src', $('iframe').attr('src'));
$('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 });
$('#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; });
$('input[type="submit"]').attr("disabled", true); $('input[type="submit"]').removeAttr("disabled");
$("div#home").prev("div"); //取得包含匹配的元素集合中每個元素緊鄰的前一個同輩元素的元素集合。 $("div#home").next("ul"); // 取得匹配的元素集合中每個元素緊鄰的後面同輩元素的元素集合 $("div#home").parent(); // 取得匹配元素集合中,每一個元素的父元素。 $("div#home").children("p"); //得到匹配元素集合中每一個元素的子元素
setInterval(function() { $("#class-id").load(location.href+" #class-id>*",""); }, 2000); // seconds to wait
var sometext = "Say something awesome"; $("p#sample1").append(sometext); // added after $("p#tsample1").prepend(sometext); // added before
$('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'); }); } });
$('#username').keyup(function() { $('#submit').attr('disabled', !$('#username').val()); });
//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'; }
<!-- 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>
<!-- 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>
(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);
<!-- 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" />
<!-- 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