jQuery代码开发技巧收集,jquery常用的开发代码
今天分享一个jquery常用的开发代码,大部分是网友总结的,总共60条。后期我也会陆续完善! 把我在开发中常用的写在这里,希望持续关注~~
1. 使用siblings()来处理同类元素
// Rather than doing this
$('#nav li').click(function(){
$('#nav li').removeClass('active');
$(this).addClass('active');
});
// Do this instead
$('#nav li').click(function(){
$(this).addClass('active').siblings().removeClass('active');
});
2. 选择或者不选页面上全部复选框
var tog = false; // or true if they are checked on load
$('a').click(function() {
$("input[type=checkbox]").attr("checked",!tog);
tog = !tog;
});
3. 基于输入文字过滤页面元素
//If the value of the element matches that of the entered text
//it will be returned
$('.gbin1Class').filter(function() {
return $(this).attr('value') == $('input#gbin1Id').val() ;
})
4. 取得鼠标的X和Y坐标
$(document).mousemove(function(e){
$(document).ready(function() {
$().mousemove(function(e){
$('#XY').html("Gbin1 X Axis : " + e.pageX + " | Gbin1 Y Axis " + e.pageY);
});
});
5. 使得整个列表元素(LI)可点击
$("ul li").click(function(){
window.location=$(this).find("a").attr("href"); return false;
});
<UL>
<LI><A href="#">GBin1 Link 1</A></LI>
<LI><A href="#">GBin1 Link 2</A></LI>
<LI><A href="#">GBin1 Link 3</A></LI>
<LI><A href="#">GBin1 Link 4</A></LI>
</UL>
6. 使用jQuery来解析XML
function parseXml(xml) {
//find every Tutorial and print the author
$(xml).find("Tutorial").each(function()
{
$("#output").append($(this).attr("author") + "");
});
}
7. 判断一个图片是否加载完全
$('#theGBin1Image').attr('src', 'image.jpg').load(function() {
alert('This Image Has Been Loaded');
});
8. 使用jQuery命名事件
//Events can be namespaced like this
$('input').bind('blur.validation', function(e){
// ...
});
//The data method also accept namespaces
$('input').data('validation.isValid', true);
9. 判断cookie是否激活或者关闭
var dt = new Date();
dt.setSeconds(dt.getSeconds() + 60);
document.cookie = "cookietest=1; expires=" + dt.toGMTString();
var cookiesEnabled = document.cookie.indexOf("cookietest=") != -1;
if(!cookiesEnabled)
{
//cookies have not been enabled
}
10.强制过期cookie
var date = new Date();
date.setTime(date.getTime() + (x * 60 * 1000));
$.cookie('example', 'foo', { expires: date });
11. 使用一个可点击的链接替换页面中所有URL
$.fn.replaceUrl = function() {
var regexp = /((ftp|http|https)://(w+:{0,1}w*@)?(S+)(:[0-9]+)?(/|/([w#!:.?+=&%@!-/]))?)/gi;
this.each(function() {
$(this).html(
$(this).html().replace(regexp,'<A href="$1">$1</A>')
);
});
return $(this);
}
//usage
$('#GBin1div').replaceUrl();
12. 在表单中禁用“回车键”
大家可能在表单的操作中需要防止用户意外的提交表单,那么下面这段代码肯定非常有帮助:
$("#form").keypress(function(e) {
if (e.which == 13) {
return false;
}
});