You are here: Home » All Categories » » jQuery 常用代码片段[转载收藏]

jQuery 常用代码片段[转载收藏]

May 13th, 2012 13:32 | Leave a comment?(54) Go to comments

前几天去 Kayo 那,看到他翻译的《50 jQuery Snippets That Will Help You Become A Better JavaScript Developer》很有收藏价值,故转载过来。好久没转载文章了,撒花~

jQuery 常用代码片段

转载自:《jQuery 常用代码片段

PS:代码木有全部验证,不敢保证 100% 正常工作


jQuery 嵌套的过滤器

过滤器可以有效对结果集就行过滤,最终得到我们想要的结果。例如下面代码就把结果集中包含有类 .selected 的元素给过滤掉了:

.filter(":not(:has(.selected))");

jQuery 缓存选择器结果集

把结果集保存在变量中缓存下来,重用时就无需再次用选择器去选择了。

var allItems = $("div.item");
var keepList = $("div#container1 div.item");

#12楼 小邪 注: 使用 “jQuery 缓存选择器结果集” 的时候如果一次选择了很多元素,要循环这些元素的时候要注意在不同浏览器下这个集数组是不同的,必须用 for in 循环,用 for count(elements) 循环到奇怪的东西
流年 反驳:不能用 for in 来遍历数组,因为不保证顺序;只能显式循环,或使用 jq 封装的 .each 函数

jQuery 检测某元素上是否包含某个类

jQuery 1.4.* 起新加的这个 has 方法:

$("input").has(".email").addClass("email_icon");

使用 jQuery 切换样式表

用选择器选择出样式表标签元素,然后改变其 href 属性的值即可。

$('link[media='screen']').attr('href', 'Alternative.css');

jQuery 限制选择器选择范围(性能优化)

尽可能地在类名前面指明标签名,这样能大大减少选择器的执行时间,如果能用 ID 之类的选择器缩小查询范围则效果更佳。

var in_stock = $('#shopping_cart_items input.is_in_stock');

假如 HTML 代码如下的话:

<ul id="shopping_cart_items">
	<li>
		<input value="Item-X" name="item" class="is_in_stock" type="radio"> Item X
	</li>
	<li>
		<input value="Item-Y" name="item" class="3-5_days" type="radio"> Item Y
	</li>
	<li>
		<input value="Item-Z" name="item" class="unknown" type="radio"> Item Z
	</li>
</ul>

jQuery ToggleClass 的正确用法

ToggleClass 用来在某元素上添加或移除某个类。

// No
a.hasClass('blueButton') ? a.removeClass('blueButton') : a.addClass('blueButton');

// Yes
a.toggleClass('blueButton');

jQuery 判断浏览器是否为 IE

if($.browser.msie) {
	// 此浏览器为 IE
} else {
	// 非 IE
}

用 jQuery 把某元素替换掉

$('#thatdiv').replaceWith('fnuh');

jQuery 判断某元素中内容是否为空

if( !$('#keks').html() ) {
	// 空空如也
}

jQuery 判断无序列表元素的索引

$("ul > li").click(function () {
    var index = $(this).prevAll().length;
});

jQuery 给元素绑定事件执行函数

$('#foo').bind('click', function() {
	alert('用户点击了 "foo"');
});

jQuery 在某元素上追加内容

$('#lal').append('sometext');

jQuery 创建元素时,用一个对象为其添加属性及属性的值

var $e = $("<div>", {
	href: "#nav",
	"class": "a-class another-class",
	title: "..."
});

注意class 是 JavaScript 的保留字,最好加上引号。

jQuery 用元素的属性作为过滤条件

而且可以用多个属性作为条件:

var elements = $('.someclass input[type=sometype][value=somevalue]').get();

jQuery 使用 delegate 为元素添加事件

自 jQuery 1.4.2 起,建议用 delegateundelegate 来替代 livedie,因为 delegate 对上下文有更好的支持。

// 使用 live()
$("table").each(function() {
	$("td", this).live("hover", function() {
		$(this).toggleClass("hover");
	});
});

// 使用 delegate()
$("table").delegate("td", "hover", function(){
	$(this).toggleClass("hover");
});

#15楼 流年 注:delegate 和 live 的对比,觉得举例不是很好,因为 live 也可以很简洁的 $('table td').live(/*..*/),更重要的是 delegate 不用冒泡到根节点上。字符串替换不应该归入到 jq 常用代码中,因为这是 js 的基本功能。

用 jQuery 找到下拉框中被选定的那个元素

$('#someElement').find('option:selected');

jQuery 将包含有某文字的段落隐藏

$("p.value:contains('thetextvalue')").hide();

jQuery 将滚动条滚动到页面上某位置

jQuery.fn.autoscroll = function() {
	$('html,body').animate({
			scrollTop: this.offset().top
		},
		500
	);
};

// 执行如下代码开始滚动,其实 autoscroll 就是一个 jQuery 插件。
$('#footer').autoscroll();

jQuery 检测浏览器版本

if( $.browser.safari ) {
	// afari
}

if( $.browser.msie && $.browser.version > 6 ) {
	// IE6 以上
}

if( $.browser.msie && $.browser.version <= 6 ) {
	// IE6 及以下
}

if( $.browser.mozilla && $.browser.version >= '1.8' ) {
	// FireFox 2 以上
}

jQuery 字符串替换

var el = $('#id');
el.html(el.html().replace(/word/ig, ''));

jQuery 禁用鼠标右键菜单

$(document).bind('contextmenu', function(e) {
	return false;
});

jQuery 检测某元素是否存在

if($('#someDiv').length) {
	// 存在
}

jQuery 侦测鼠标左击和右击事件

$("#someelement").live('click', function(e) {
	if( (!$.browser.msie && e.button == 0) || ($.browser.msie && e.button == 1) ) {
		alert("左击了");
	} else if(e.button == 2) {
		alert("右击了");
	}
});

jQuery 自动显示、隐藏文本框的默认值

swap_val = [];
$("#s").each(function(i) {
	swap_val[i] = $(this).val();
	$(this).focusin(function() {
		if($(this).val() == swap_val[i]) {
			$(this).val("");
		}
	}).focusout(function() {
		if ($.trim($(this).val()) == "") {
			$(this).val(swap_val[i]);
		}
	});
});

假如文本框 HTML 代码如下的话

<input value="Enter the keyword to search..." id="s" type="text">

jQuery 延时执行 JavaScript 代码

// 1.4 之前版本
setTimeout(function() {
	$('.mydiv').hide('blind', {}, 500);
}, 5000);

// 1.4 及之后版本
$(".mydiv").delay(5000).hide('blind', {}, 500);

jQuery 创建新元素并添加到页面中

var $newDiv = $('<div>');
$newDiv.attr('id','myNewDiv').appendTo('body');

jQuery 限制文本框中字符数

// 插件代码
jQuery.fn.maxLength = function(max) {
	this.each(function() {
		var type = this.tagName.toLowerCase();
		var inputType = this.type ? this.type.toLowerCase() : null;
		if(type == "input" && inputType == "text" || inputType == "password") {
			// 最大字符数
			this.maxLength = max;
		} else if(type == "textarea") {
			this.onkeypress = function(e) {
				var ob = e || event;
				var keyCode = ob.keyCode;
				var hasSelection = 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);
				}
			};
		}
	});
};

// 使用方法
$('#comment').maxLength(20);

jQuery 如何克隆一个元素

var $cloned = $('#somediv').clone();

jQuery 检测某元素是否处于可见状态

if($(element).is(':visible') == 'true') {
	// 可见
}

#15楼 流年 注:检测可见不用多作判断,直接 .is(':visible')

jQuery 让某元素居中显示

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');
	return this;
};

// 使用方法
$(element).center();

jQuery 将一批元素的值存到一个数组中

var arrInputValues = new Array();

$("input.someclass").each(function() {
     arrInputValues.push($(this).val());
});

jQuery 剥离 HTML 代码

(function($) {
    $.fn.stripHtml = function() {
        var regexp = /<("[^"]*"|'[^']*'|[^'">])*>/gi;
        this.each(function() {
            $(this).html(
                $(this).html().replace(regexp,"")
            );
        });
        return $(this);
    }
})(jQuery);

//用法
$('p').stripHtml();

jQuery 使用 closest 获取父元素

$('#searchBox').closest('div');

#4楼 牧风 注:closest 不只是获取父元素, 是获取离此元素最近的(xxoo)元素

jQuery 在新窗口中打开超链接

jQuery(document).delegate('a', 'click', function() {
	var root = location.href.replace(location.pathname + location.search + location.hash, '');

	if ( !this.href ) return;

	if ( this.href.indexOf(root) != 0 ) {
		window.open(this.href);
		return false;
	}
});

jQuery 使用 .siblings() 获取姊妹元素

// 这样可以
$('#nav li').click(function() {
	$('#nav li').removeClass('active');
	$(this).addClass('active');
});

// 这样更好
$('#nav li').click(function() {
	$(this).addClass('active')
		.siblings().removeClass('active');
});

jQuery 让页面中所有复选框选中或者非选中

var tog = false;
$('a').click(function() {
	$("input[type=checkbox]").attr("checked", !tog);
	tog = !tog;
});

jQuery 根据特定元素值过滤的过滤器

$('.someClass').filter(function() {
	return $(this).attr('value') == $('input#someId').val();
});

jQuery 获取鼠标指针的坐标

$(document).ready(function() {
	$(document).mousemove(function(e) {
		$('#XY').html('X 坐标 : ' + e.pageX + ' | Y 坐标 : ' + e.pageY);
	});
});

jQuery 让整个 List 元素可点击

$("ul li").click(function() {
	window.location=$(this).find("a").attr("href");
	return false;
});

示例 HTML 代码

<ul>
	<li><a href="#">Link 1</a></li>
	<li><a href="#">Link 2</a></li>
	<li><a href="#">Link 3</a></li>
	<li><a href="#">Link 4</a></li>
</ul>

jQuery 解析 XML 的简单示例

function parseXml(xml) {
	$(xml).find("Tutorial").each(function() {
		$("#output").append($(this).attr("author") + " ");
	});
}

jQuery 检测图片是否加载完毕

$('#theImage').attr('src', 'image.jpg').load(function() {
	alert('图片加载完毕!');
});

jQuery 事件及方法的命名空间

// 事件
$('input').bind('blur.validation', function(e) {
	// ...
});

// 方法
$('input').data('validation.isValid', true);

jQuery 检测浏览器是否启用了 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) {
        // 未启用
}

jQuery 让 cookie 过期

var date = new Date();
date.setTime(date.getTime() + (x * 60 * 1000));
$.cookie('example', 'foo', { expires: date });

jQuery 自动为网址加上超链接

$.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);
};

// 用法
$('p').replaceUrl();

声明: 除非注明,ZWWoOoOo文章均为原创,转载请以链接形式标明本文地址
本文地址: http://zww.me/archives/25647

Filed under

| Tags:

,

Related Posts

Most Popular

54 Comments.

⊕Leave a comment?
  1. Feeng Feeng Google Chrome 18.0.1025.168Windows 7

    同收藏。感谢。

    沙发!软软很舒服!1
  2. chisdy chisdy Google Chrome 18.0.1025.168Windows 7

    这个很有用,收藏~

    板凳!有点硬!2
  3. axiu axiu Google Chrome 18.0.1025.168Windows 7

    有几个眼生的,有空拿去试试 :mrgreen:

    地板!又硬又冷!3
  4. 牧风 牧风 Google Chrome 18.0.1025.168Windows 7

    closest 不只是获取父元素, 是获取离此元素最近的(xxoo)元素

    4楼
  5. Justice Justice Firefox 12.0Windows XP

    jQuery 判断某元素中内容是否为空
    判断条件里面少了个 "!"。

    5楼
  6. 久酷 久酷 Firefox 11.0.1Windows 7

    确实呀 不常用的话 很容易忘记

    6楼
  7. wmtimes wmtimes Google Chrome 18.0.1025.162Windows 7

    我也收藏下。呵呵。

    7楼
  8. 不能吧 不能吧 Opera 11.64Windows XP

    好多天书啊 :lol:

    8楼
  9. 咚门 咚门 Google Chrome 18.0.1025.168Windows 7

    哇塞,太强大了这篇文章,以后可以直接到这来找了。

    9楼
  10. airoschou airoschou Google Chrome 18.0.1025.168Windows XP

    对于前端工程狮来说简直太有用啦,哈哈 :lol:

    10楼
  11. Normal Normal Firefox 12.0Windows 7 x64 Edition

    :mrgreen: :mrgreen: 我抄走了。。

    11楼
  12. 小邪 小邪 Google Chrome 19.0.1084.9Windows 7 x64 Edition

    使用 “jQuery 缓存选择器结果集” 的时候如果一次选择了很多元素,要循环这些元素的时候要注意在不同浏览器下这个集数组是不同的,必须用 for in 循环,用 for count(elements) 循环到奇怪的东西 >//<

    12楼
    • zwwooooo zwwooooo Firefox 12.0Windows 7 x64 Edition

      @小邪
      小邪玩的透彻些,用到时得注意一下。

    • 流年 流年 Chromium 18.0.1025.168Ubuntu 12.04 x64

      @小邪
      不能用 for in 来遍历数组,因为不保证顺序;只能显式循环,或使用 jq 封装的 .each 函数

    • 小邪 小邪 Google Chrome 19.0.1084.46Windows 7 x64 Edition

      @流年
      啊啊,目前木有碰到顺序问题,不过的确有可能出现隐患。
      多谢.each的建议,迟一些用这个改良一下代码。
      求教什么是显式?这东西google不到啊 >w<

    • 小邪 小邪 Google Chrome 19.0.1084.46Windows 7 x64 Edition

      @zwwooooo
      最近被逼的 >w<

    • 流年 流年 Chromium 18.0.1025.168Ubuntu 12.04 x64

      @小邪
      哦,其实我想说的是常规的 for 循环 :evil:

      for (var i=0, l=arr.length; i<l; i+=){}
      
    • 小邪 小邪 Google Chrome 19.0.1084.46Mac OS X 10.7.4

      @流年
      额 这个方法在firefox里面会循环到奇怪的东西。。。。
      我用 ele = $("#wrapper .itemlist .post") 取了元素,但是在 firefox 里面会循环到整个页面的元素,其他浏览器正常。。。
      额,难道是我没在后面加 toArray()?

    • 流年 流年 Chromium 18.0.1025.168Ubuntu 10.04

      @小邪
      虽说 jq 选择到的元素不是真正的数组而是 jq 对象,但应该不会发生这种情况啊;在 ff 12 中实践了一下,正常。

      不过,对于 jq,可以依赖于隐式循环(比如事件处理等),或用 each

    • 小邪 小邪 Google Chrome 19.0.1084.46Windows 7 x64 Edition

      @流年
      啊啊,之前是mac版的ff,也有可能是我哪里写错影响到这里了 >_<。
      用jq的时候还是用each吧,额,对了,each有办法知道目前的索引么?就是如果是 for x in 的时候的 x 。=w=

    • 流年 流年 Chromium 18.0.1025.168Ubuntu 12.04 x64

      @小邪
      each 的时候,第一个参数是 index,第二格参数是对应的 value, this 也是指向 value; 可参考文档 jQuery.each

    • 小邪 小邪 Google Chrome 19.0.1084.46Windows 7 x64 Edition

      @流年
      Thx 应该多看看文档呐 >w<

  13. 星野苍真 星野苍真 Firefox 12.0Windows 7

    先收藏,晚上有时间再来看 :lol:

    13楼
  14. Kayo Kayo Google Chrome 18.0.1025.162Windows 7

    非常值得收藏,感谢!
    话说我也是Kayo呢! :razz:

    14楼
  15. 流年 流年 Chromium 18.0.1025.168Ubuntu 10.04

    挑刺
    1. 判断元素内容为空处少了个

    !

    2. 无需列表 -> 无序列表
    3. 检测可见不用多作判断,直接

    .is(':visible')

    即可。

    另:

    delegate

    live

    的对比,觉得举例不是很好,因为 live 也可以很简洁的

    $('table td').live(/*..*/)

    ,更重要的是 delegate 不用冒泡到根节点上。

    字符串替换不应该归入到 jq 常用代码中,因为这是 js 的基本功能。

    15楼
  16. 郑永 郑永 Google Chrome 18.0.1025.151Windows XP

    搞网站的,都爱收藏,嘿嘿:)

    16楼
  17. 刘印博客 刘印博客 360Safe ExplorerWindows 7 x64 Edition

    收藏下不错,要用的时候可以用刀!!

    17楼
  18. Dick_Wu Dick_Wu Google Chrome 21.0.1144.0Windows 7

    这两天搞一个小网页,需要搞搞jQuery,谢Z大整理啦!

    18楼
  19. Demon Demon Google Chrome 19.0.1084.52Windows 7

    好东东。收藏备用。 :mrgreen:

    19楼
  20. 小小 小小 Google Chrome 20.0.1123.4Windows 7

    传说中的技术手册啊!!

    20楼
  21. Crystal Pendant Crystal Pendant Firefox 14.0.1Windows 7 x64 Edition

    碉堡了,看JQUERY手册没有发现有这么多应用啊,这随便组合了一下就这么多了够折腾的,不过功能的确很强大。

    21楼
  22. 倡萌 倡萌 Google Chrome 18.0.1025.142Windows XP

    没学过jQuery,有机会好好学习一下

    22楼
  23. kn007 kn007 Firefox 15.0.1Windows XP

    学习一下。 :mrgreen:

    23楼

Leave a Reply


Welcome! o(∩_∩)o
X