jQuery 常用代码集锦(必看篇)
1. 选择或者不选页面上全部复选框
vartog=false;//ortrueiftheyarecheckedonload
$('a').click(function(){
$("input[type=checkbox]").attr("checked",!tog);
tog=!tog;
});
2.取得鼠标的X和Y坐标
$(document).mousemove(function(e){
$(document).ready(function(){
$().mousemove(function(e){
$('#XY').html("Gbin1XAxis:"+e.pageX+"|Gbin1YAxis"+e.pageY);
});
});
3.判断一个图片是否加载完全
$('#theGBin1Image').attr('src','image.jpg').load(function(){
alert('ThisImageHasBeenLoaded');
});
4.判断cookie是否激活或者关闭
vardt=newDate();
dt.setSeconds(dt.getSeconds()+60);
document.cookie="cookietest=1;expires="+dt.toGMTString();
varcookiesEnabled=document.cookie.indexOf("cookietest=")!=-1;
if(!cookiesEnabled)
{
//cookieshavenotbeenenabled
}
5.强制过期cookie
vardate=newDate();
date.setTime(date.getTime()+(x*60*1000));
$.cookie('example','foo',{expires:date});
6.在表单中禁用“回车键”,表单的操作中需要防止用户意外的提交表单
$("#form").keypress(function(e){
if(e.which==13){
returnfalse;
}
});
7.清除所有的表单数据
functionclearForm(form){
//iterateoveralloftheinputsfortheform
//elementthatwaspassedin
$(':input',form).each(function(){
vartype=this.type;
vartag=this.tagName.toLowerCase();//normalizecase
//it'soktoresetthevalueattroftextinputs,
//passwordinputs,andtextareas
if(type=='text'||type=='password'||tag=='textarea')
this.value="";
//checkboxesandradiosneedtohavetheircheckedstatecleared
//butshould*not*havetheir'value'changed
elseif(type=='checkbox'||type=='radio')
this.checked=false;
//selectelementsneedtohavetheir'selectedIndex'propertysetto-1
//(thisworksforbothsingleandmultipleselectelements)
elseif(tag=='select')
this.selectedIndex=-1;
});
};
8.禁止多次递交表单
$(document).ready(function(){
$('form').submit(function(){
if(typeofjQuery.data(this,"disabledOnSubmit")=='undefined'){
jQuery.data(this,"disabledOnSubmit",{submited:true});
$('input[type=submit],input[type=button]',this).each(function(){
$(this).attr("disabled","disabled");
});
returntrue;
}
else
{
returnfalse;
}
});
});
9.自动将数据导入selectbox中
$(function(){
$("select#ctlJob").change(function(){
$.getJSON("/select.php",{id:$(this).val(),ajax:'true'},function(j){
varoptions='';
for(vari=0;i<j.length;i++){
options+='<optionvalue="'+j[i].optionValue+'">'+j[i].optionDisplay+'</option>';
}
$("select#ctlPerson").html(options);
})
})
})
10.创建一个嵌套的过滤器
.filter(":not(:has(.selected))")//去掉所有不包含class为.selected的元素
11.使用has()来判断一个元素是否包含特定的class或者元素
//jQuery1.4.*includessupportforthehasmethod.Thismethodwillfind
//ifaanelementcontainsacertainotherelementclassorwhateveritis
//youarelookingforanddoanythingyouwanttothem.
$("input").has(".email").addClass("email_icon");
12.使用jQuery切换样式
//Lookforthemedia-typeyouwishtoswitchthensetthehreftoyournewstylesheet
$('link[media='screen']').attr('href','Alternative.css');
13.如何正确使用ToggleClass
//Toggleclassallowsyoutoaddorremoveaclass
//fromanelementdependingonthepresenceofthat
//class.Wheresomedeveloperswoulduse:
a.hasClass('blueButton')?a.removeClass('blueButton'):a.addClass('blueButton');
//toggleClassallowsyoutoeasilydothisusing
a.toggleClass('blueButton');
14.使用jQuery来替换一个元素
$('#thatdiv').replaceWith('fnuh');
15.绑定一个函数到一个事件
$('#foo').bind('click',function(){
alert('Userclickedon"foo."');
});
16.使用jQuery预加载图片
jQuery.preloadImages=function(){for(vari=0;i').attr('src',arguments[i]);}};
//Usage$.preloadImages('image1.gif','/path/to/image2.png','some/image3.jpg');
17.设置任何匹配一个选择器的事件处理程序
$('button.someClass').live('click',someFunction);
//NotethatinjQuery1.4.2,thedelegateandundelegateoptionshavebeen
//introducedtoreplaceliveastheyofferbettersupportforcontext
//Forexample,intermsofatablewherebeforeyouwoulduse..
//.live()
$("table").each(function(){
$("td",this).live("hover",function(){
$(this).toggleClass("hover");
});
});
//Nowuse..
$("table").delegate("td","hover",function(){
$(this).toggleClass("hover");
});
18.自动的滚动到页面特定区域
jQuery.fn.autoscroll=function(selector){
$('html,body').animate(
{scrollTop:$(selector).offset().top},
);
}
//Thentoscrolltotheclass/areayouwishtogettolikethis:
$('.area_name').autoscroll();
19.检测各种浏览器
DetectSafari(if($.browser.safari)), DetectIE6andover(if($.browser.msie&&$.browser.version>6)), DetectIE6andbelow(if($.browser.msie&&$.browser.version<=6)), DetectFireFox2andabove(if($.browser.mozilla&&$.browser.version>='1.8')
20.限制textarea的字符数量
jQuery.fn.maxLength=function(max){
this.each(function(){
vartype=this.tagName.toLowerCase();
varinputType=this.type?this.type.toLowerCase():null;
if(type=="input"&&inputType=="text"||inputType=="password"){
//ApplythestandardmaxLength
this.maxLength=max;
}
elseif(type=="textarea"){
this.onkeypress=function(e){
varob=e||event;
varkeyCode=ob.keyCode;
varhasSelection=document.selection?document.selection.createRange().text.length>0:this.selectionStart!=this.selectionEnd;
return!(this.value.length>=max&&(keyCode>50||keyCode==32||keyCode==0||keyCode==13)&&!ob.ctrlKey&&!ob.altKey&&!hasSelection);
};
this.onkeyup=function(){
if(this.value.length>max){
this.value=this.value.substring(0,max);
}
};
}
});
};
//Usage:
$('#gbin1textarea').maxLength(500);
21.使用jQuery克隆元素
varcloned=$('#gbin1div').clone();
22.元素屏幕居中
jQuery.fn.center=function(){
this.css('position','absolute');
this.css('top',($(window).height()-this.height())/+$(window).scrollTop()+'px');
this.css('left',($(window).width()-this.width())/2+$(window).scrollLeft()+'px');returnthis;
}
//Usetheabovefunctionas:$('#gbin1div').center();
23.简单的tab标签切换
jQuery('#meeting_tabsulli').click(function(){
jQuery(this).addClass('tabulous_active').siblings().removeClass('tabulous_active');
jQuery('#tabs_container>.pane:eq('+jQuery(this).index()+')').show().siblings().hide();
})
<divid="meeting_tabs">
<ul>
<liclass="tabulous_active"><ahref="#"title="">进行中</a></li>
<li><ahref="#"title="">未开始</a></li>
<li><ahref="#"title="">已结束</a></li>
<li><ahref="#"title="">全部</a></li>
</ul>
<divid="tabs_container">
<divclass="pane">1</div>
<divclass="pane">2</div>
<divclass="pane">3</div>
<divclass="pane">4</div>
</div>
</div>
以上这篇jQuery常用代码集锦(必看篇)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。