如今,JQuery 已被普遍的利于用网站建设,下面介绍一些经常使用的代码片断,收藏。javascript
常常出如今网站右侧,向上箭头同样的东西,方便咱们回到网站头部。给出代码片断,给连接一个id top:php
$("a[href='#top']").click(function() { $("html, body").animate({ scrollTop: 0 }, "slow"); return false; });
为了表格的可读性。咱们常常将表头复制一份丢在表的底部。这里给出 JQuery 片断,能帮咱们完成这个功能: var $tfoot = $(''); $($('thead').clone(true, true).children().get().reverse()).each(function(){ $tfoot.append($(this)); }); $tfoot.insertAfter('table thead');css
在jquery中,咱们用如下方法很容易作到,加载面的信息进咱们的div中: html
$("#content").load("somefile.html", function(response, status, xhr) { // error handling if(status == "error") { $("#content").html("An error occured: " + xhr.status + " " + xhr.statusText); } });
在web的内容显示上。咱们常常将内容高度统一,这样看上去会更加美观一些。 java
var maxheight = 0; $("div.col").each(function(){ if($(this).height() > maxheight) { maxheight = $(this).height(); } }); $("div.col").height(maxheight);
当显示一个表的数据,不一样的颜色在每一行确定会增长可读性。 jquery
$(document).ready(function(){ $("table tr:even").addClass('stripe'); });
当你须要刷新网站部份内容时候能够用到下面的片断,每10秒刷新一次div:
setInterval(function() { $("#refresh").load(location.href+" #refresh>*",""); }, 10000); // milliseconds to waitweb
$.preloadImages = function() { for(var i = 0; i<arguments.length; i++) { $("<img />").attr("src", arguments[i]); } } $(document).ready(function() { $.preloadImages("hoverimage1.jpg","hoverimage2.jpg"); });
target="blank" 这个属性容许咱们在新窗口打开连接。咱们这里能够利用jquery代码来批量控制网站之外连接经过新窗口打开ajax
$('a').each(function() { var a = new RegExp('/' + window.location.host + '/'); if(!a.test(this.href)) { $(this).click(function(event) { event.preventDefault(); event.stopPropagation(); window.open(this.href, '_blank'); }); } });
html: <input type="password" name="pass" /> <span></span>
在正则表达式中判断密码强弱并返回信息 正则表达式
$('#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; });
ajax滚动加载信息到列表中显示app
var loading = false; $(window).scroll(function(){ if((($(window).scrollTop()+$(window).height())+250)>=$(document).height()){ if(loading == false){ loading = true; $('#loadingbar').css("display","block"); $.get("load.php?start="+$('#loaded_max').val(), function(loaded){ $('body').append(loaded); $('#loaded_max').val(parseInt($('#loaded_max').val())+50); $('#loadingbar').css("display","none"); loading = false; }); } } }); $(document).ready(function() { $('#loaded_max').val(50); });