JQuery常用的代码片段
生活随笔
收集整理的這篇文章主要介紹了
JQuery常用的代码片段
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
2019獨角獸企業重金招聘Python工程師標準>>>
JQuery常用的代碼片段 JQuery在當前眾多網站開發中都有用到。他簡易的操作以及對各個瀏覽器的兼容性,被廣大的開發者一致看好。 下面是一些常用實用的 JQuery 代碼片段。看看有沒有需要收藏的吧:
1. 阻止鏈接點擊
$("a").on("click", function(e){e.preventDefault(); });2. 幻燈片切入
// Fade $( “.btn" ).click(function() { $( “.element" ).fadeToggle("slow"); });// Toggle $( “.btn" ).click(function() { $( “.element" ).slideToggle("slow"); });當我們需要在當前一面加載一個div或其他標簽的時候十分有效。
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.回到頂部
// 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 handlingif(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 wait16.增加元素
var sometext = "Say something awesome"; $("p#sample1").append(sometext); // added after $("p#tsample1").prepend(sometext); // added before17.新窗口打開外部鏈接
$('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>結束
以上就是一些經常用到的代碼片段了。由于經常使用。不妨收藏一下
轉載于:https://my.oschina.net/u/265943/blog/292873
總結
以上是生活随笔為你收集整理的JQuery常用的代码片段的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 偷窃转基因玉米种子引发中美打农业官司
- 下一篇: net.sf.json.JSONObje