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 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>
结束
以上就是一些经常用到的代码片段了。由于经常使用。不妨收藏一下