ITeye博客

50个jQuery代码段帮你成为更好的JavaScript开发者

nolan022 · 2011-08-15 10:39 · Web前端 · Markdown

今天的帖子会给你们展示50个jquery代码片段,这些代码能够给你的javascript项目提供帮助。其中的一些代码段是从jQuery1.4.2才开始支持的做法,另一些则是真正有用的函数或方法,他们能够帮助你又快又好地把事情完成。这些都是我尽量记住的有着最佳性能的代码段,因此如果你发现你任何可以做得更好的地方的话,欢迎把你的版本粘贴在评论中!我希望你在这一文章中能找到有帮助的东西。

1. 如何创建嵌套的过滤器:

view source

print?

1 //允许你减少集合中的匹配元素的过滤器,

2 //只剩下那些与给定的选择器匹配的部分。在这种情况下,

3 //查询删除了任何没(:not)有(:has)

4 //包含class为“selected”(.selected)的子节点。

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

2. 如何重用元素搜索

view source

print?

01 var allItems = $("div.item");

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

03 //现在你可以继续使用这些jQuery对象来工作了。例如,

04 //基于复选框裁剪“keep list”,复选框的名称

05 //符合

06 < DIV >class names:

07 $(formToLookAt + " input:checked").each(function() {

08 keepList = keepList.filter("." + $(this).attr("name"));

09 });

10 < /DIV>

3. 任何使用has()来检查某个元素是否包含某个类或是元素:

view source

print?

1  

 

view source

print?

1 //jQuery 1.4.*包含了对这一has方法的支持。该方法找出

2 //某个元素是否包含了其他另一个元素类或是其他任何的

3 //你正在查找并要在其之上进行操作的东东。

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

4. 如何使用jQuery来切换样式表

view source

print?

1 //找出你希望切换的媒体类型(media-type),然后把href设置成新的样式表。

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

5. 如何限制选择范围(基于优化目的):

view source

print?

1 //尽可能使用标签名来作为类名的前缀,

2 //这样jQuery就不需要花费更多的时间来搜索

3 //你想要的元素。还要记住的一点是,

4 //针对于你的页面上的元素的操作越具体化,

5 //就越能降低执行和搜索的时间。

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

view source

print?

1 <ul id="shopping_cart_items">

2 <li><input type="radio" value="Item-X" name="item" class="is_in_stock" /> Item X</li>

3 <li><input type="radio" value="Item-Y" name="item" class="3-5_days" /> Item Y</li>

4 <li><input type="radio" value="Item-Z" name="item" class="unknown" /> Item Z</li>

5 </ul>

6. 如何正确地使用ToggleClass:

view source

print?

1 //切换(toggle)类允许你根据某个类的

2 //是否存在来添加或是删除该类。

3 //这种情况下有些开发者使用:

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

5 //toggleClass允许你使用下面的语句来很容易地做到这一点

6 a.toggleClass('blueButton');

7. 如何设置IE特有的功能:

view source

print?

1 if ($.browser.msie) {

2 // Internet Explorer就是个虐待狂

3 }

8. 如何使用jQuery来代替一个元素:

view source

print?

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

9. 如何验证某个元素是否为空:

view source

print?

1 if ($('#keks').html()) {

2 //什么都没有找到;

3 }

10. 如何从一个未排序的集合中找出某个元素的索引号

view source

print?

1 $("ul > li").click(function () {

2 var index = $(this).prevAll().length;

3 });

11. 如何把函数绑定到事件上:

view source

print?

1 $('#foo').bind('click', function() {

2 alert('User clicked on "foo."');

3 });

12. 如何追加或是添加html到元素中:

view source

print?

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

13. 在创建元素时,如何使用对象字面量(literal)来定义属性

view source

print?

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

14. 如何使用多个属性来进行过滤

view source

print?

1 //在使用许多相类似的有着不同类型的input元素时,

2 //这种基于精确度的方法很有用

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

15. 如何使用jQuery来预加载图像:

view source

print?

1 jQuery.preloadImages = function() {

2 for(var i = 0; i < arguments.length; i++) {

3 $("<img />").attr('src', arguments[i]);

4 }

5 };

6 //用法

7 $.preloadImages('image1.gif', '/path/to/image2.png', 'some/image3.jpg');

16. 如何为任何与选择器相匹配的元素设置事件处理程序:

view source

print?

01 $('button.someClass').live('click', someFunction);

02 //注意,在jQuery 1.4.2中,delegate和undelegate选项

03 //被引入代替live,因为它们提供了更好的上下文支持

04 //例如,就table来说,以前你会用

05 //.live()

06 $("table").each(function(){

07 $("td", this).live("hover", function(){

08 $(this).toggleClass("hover");

09 });

10 });

11 //现在用

12 $("table").delegate("td", "hover", function(){

13 $(this).toggleClass("hover");

14 });

17. 如何找到一个已经被选中的option元素:

view source

print?

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

18. 如何隐藏一个包含了某个值文本的元素:

view source

print?

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

19. 如果自动滚动到页面中的某区域

view source

print?

1 jQuery.fn.autoscroll = function(selector) {

2 $('html,body').animate(

3 {scrollTop: $(selector).offset().top},

4 500

5 };

6 }

7 //然后像这样来滚动到你希望去到的class/area上。

8 $('.area_name').autoscroll();

20. 如何检测各种浏览器:

view source

print?

1 检测Safari (if( $.browser.safari)),

2 检测IE6及之后版本 (if ($.browser.msie && $.browser.version > 6 )),

3 检测IE6及之前版本 (if ($.browser.msie && $.browser.version <= 6 )),

4 检测FireFox 2及之后版本 (if ($.browser.mozilla && $.browser.version >= '1.8' ))

21. 如何替换串中的词

view source

print?

1 var el = $('#id');

2 el.html(el.html().replace(/word/ig, ''));

22. 如何禁用右键单击上下文菜单:

view source

print?

1 $(document).bind('contextmenu',function(e){

2 return false;

3 });

23. 如何定义一个定制的选择器

view source

print?

1 $.expr[':'].mycustomselector = function(element, index, meta, stack){

2 // element- 一个DOM元素

3 // index – 栈中的当前循环索引

4 // meta – 有关选择器的元数据

5 // stack – 要循环的所有元素的栈

6 // 如果包含了当前元素就返回true

7 // 如果不包含当前元素就返回false };

8 // 定制选择器的用法:

9 $('.someClasses:test').doSomething();

24. 如何检查某个元素是否存在

view source

print?

1 if ($('#someDiv').length) {

2 //万岁!!!它存在……

3 }

25. 如何使用jQuery来检测右键和左键的鼠标单击两种情况:

view source

print?

1 $("#someelement").live('click', function(e) {

2 if( (!$.browser.msie && e.button == 0) || ($.browser.msie && e.button == 1) ) {

3 alert("Left Mouse Button Clicked");

4 } else if(e.button == 2) {

5 alert("Right Mouse Button Clicked");

6 }

7 });

26. 如何显示或是删除input域中的默认值

view source

print?

01 //这段代码展示了在用户未输入值时,

02 //如何在文本类型的input域中保留

03 //一个默认值

04 wap_val = [];

05 $(".swap").each(function(i){

06 wap_val[i] = $(this).val();

07 $(this).focusin(function(){

08 if ($(this).val() == swap_val[i]) {

09 $(this).val("");

10 }

11 }).focusout(function(){

12 if ($.trim($(this).val()) == "") {

13 $(this).val(swap_val[i]);

14 }

15 });

16 });

view source

print?

1 <input type="text" value="Enter Username here.." class="swap" />

27. 如何在一段时间之后自动隐藏或关闭元素(支持1.4版本):

view source

print?

1 //这是1.3.2中我们使用setTimeout来实现的方式

2 setTimeout(function() {

3 $('.mydiv').hide('blind', {}, 500)

4 }, 5000);

5 //而这是在1.4中可以使用delay()这一功能来实现的方式(这很像是休眠)

6 $(".mydiv").delay(5000).hide('blind', {}, 500);

28. 如何把已创建的元素动态地添加到DOM中:

view source

print?

1 var newDiv = $('');

2 newDiv.attr('id','myNewDiv').appendTo('body');

29. 如何限制“Text-Area”域中的字符的个数:

view source

print?

01 jQuery.fn.maxLength = function(max){

02 this.each(function(){

03 var type = this.tagName.toLowerCase();

04 var inputType = this.type? this.type.toLowerCase() : null;

05 if(type == "input" && inputType == "text" || inputType == "password"){

06 //Apply the standard maxLength

07 this.maxLength = max;

08 }

09 else if(type == "textarea"){

10 this.onkeypress = function(e){

11 var ob = e || event;

12 var keyCode = ob.keyCode;

13 var hasSelection = document.selection? document.selection.createRange().text.length > 0 : this.selectionStart != this.selectionEnd;

14 return !(this.value.length >= max && (keyCode > 50 || keyCode == 32 || keyCode == 0 || keyCode == 13) && !ob.ctrlKey && !ob.altKey && !hasSelection);

15 };

16 this.onkeyup = function(){

17 if(this.value.length > max){

18 this.value = this.value.substring(0,max);

19 }

20 };

21 }

22 });

23 };

24 //用法

25 $('#mytextarea').maxLength(500);

30. 如何为函数创建一个基本的测试

view source

print?

1 //把测试单独放在模块中

2 module("Module B");

3 test("some other test", function() {

4 //指明测试内部预期有多少要运行的断言

5 expect(2);

6 //一个比较断言,相当于JUnit的assertEquals

7 equals( true, false, "failing test" );

8 equals( true, true, "passing test" );

9 });

31. 如何在jQuery中克隆一个元素:

view source

print?

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

32. 在jQuery中如何测试某个元素是否可见

view source

print?

1 if($(element).is(':visible') == 'true') {

2 //该元素是可见的

3 }

33. 如何把一个元素放在屏幕的中心位置:

view source

print?

1 jQuery.fn.center = function () {

2 this.css('position','absolute');

3 this.css('top', ( $(window).height() - this.height() ) / +$(window).scrollTop() + 'px');

4 this.css('left', ( $(window).width() - this.width() ) / 2+$(window).scrollLeft() + 'px');

5 return this;

6 }

7 //这样来使用上面的函数:

8 $(element).center();

34. 如何把有着某个特定名称的所有元素的值都放到一个数组中:

view source

print?

1 var arrInputValues = new Array();

2 $("input[name='table[]']").each(function(){

3 arrInputValues.push($(this).val());

4 });

35. 如何从元素中除去html

view source

print?

01 (function($) {

02 $.fn.stripHtml = function() {

03 var regexp = /<("[^"]*"|'[^']*'|[^'">])*>/gi;

04 this.each(function() {

05 $(this).html( $(this).html().replace(regexp,”") );

06 });

07 return $(this);

08 }

09 })(jQuery);

10 //用法:

11 $('p').stripHtml();

36. 如何使用closest来取得父元素:

view source

print?

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

37. 如何使用Firebug和Firefox来记录jQuery事件日志:

view source

print?

1 // 允许链式日志记录

2 // 用法:

3 $('#someDiv').hide().log('div hidden').addClass('someClass');

4 jQuery.log = jQuery.fn.log = function (msg) {

5 if (console){

6 console.log("%s: %o", msg, this);

7 }

8 return this;

9 };

38. 如何强制在弹出窗口中打开链接:

view source

print?

1 jQuery('a.popup').live('click', function(){

2 newwindow=window.open($(this).attr('href'),'','height=200,width=150');

3 if (window.focus) {

4 newwindow.focus();

5 }

6 return false;

7 });

39. 如何强制在新的选项卡中打开链接:

view source

print?

1 jQuery('a.newTab').live('click', function(){

2 newwindow=window.open($(this).href);

3 jQuery(this).target = "_blank";

4 return false;

5 });

40. 在jQuery中如何使用.siblings()来选择同辈元素

view source

print?

1 // 不这样做

2 $('#nav li').click(function(){

3 $('#nav li').removeClass('active');

4 $(this).addClass('active');

5 });

6 //替代做法是

7 $('#nav li').click(function(){

8 $(this).addClass('active').siblings().removeClass('active');

9 });

41. 如何切换页面上的所有复选框:

view source

print?

1 var tog = false;

2 // 或者为true,如果它们在加载时为被选中状态的话

3 $('a').click(function() {

4 $("input[type=checkbox]").attr("checked",!tog);

5 tog = !tog;

6 });

42. 如何基于一些输入文本来过滤一个元素列表:

view source

print?

1 //如果元素的值和输入的文本相匹配的话

2 //该元素将被返回

3 $('.someClass').filter(function() {

4 return $(this).attr('value') == $('input#someId').val();

5 })

43. 如何获得鼠标垫光标位置x和y

view source

print?

1 $(document).ready(function() {

2 $(document).mousemove(function(e){

3 $(’#XY’).html(”X Axis : ” + e.pageX + ” | Y Axis ” + e.pageY);

4 });

5 });

44. 如何把整个的列表元素(List Element,LI)变成可点击的

view source

print?

1 $("ul li").click(function(){

2 window.location=$(this).find("a").attr("href");

3 return false;

4 });

view source

print?

1 <ul>

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

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

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

5 <li><a href="#">Link 4</a></li>

6 </ul>

45. 如何使用jQuery来解析XML(基本的例子):

view source

print?

1 function parseXml(xml) {

2 //找到每个Tutorial并打印出author

3 $(xml).find("Tutorial").each(function() {

4 $("#output").append($(this).attr("author") + "");

5 });

6 }

46. 如何检查图像是否已经被完全加载进来

view source

print?

1 $('#theImage').attr('src', 'image.jpg').load(function() {

2 alert('This Image Has Been Loaded');

3 });

47. 如何使用jQuery来为事件指定命名空间:

view source

print?

1 //事件可以这样绑定命名空间

2 $('input').bind('blur.validation', function(e){

3 // ...

4 });

5 //data方法也接受命名空间

6 $('input').data('validation.isValid', true);

48. 如何检查cookie是否启用

view source

print?

1 var dt = new Date();

2 dt.setSeconds(dt.getSeconds() + 60);

3 document.cookie = "cookietest=1; expires=" + dt.toGMTString();

4 var cookiesEnabled = document.cookie.indexOf("cookietest=") != -1;

5 if(!cookiesEnabled) {

6 //没有启用cookie

7 }

49. 如何让cookie过期:

view source

print?

1 var date = new Date();

2 date.setTime(date.getTime() + (x * 60 * 1000));

3 $.cookie('example', 'foo', { expires: date });

50. 如何使用一个可点击的链接来替换页面中任何的URL

view source

print?

01 $.fn.replaceUrl = function() {

02 var regexp = /((ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?)/gi;

03 this.each(function() {

04 $(this).html(

05 $(this).html().replace(regexp,'<A href="$1">$1</A>‘)

06 );

07 });

08 return $(this);

09 }

10 //用法

11 $('p').replaceUrl();

由我爱互联网于2011年8月12日校验修订。

本文永久链接:http://www.woiweb.net/50-jquery-snippets-for-developers.html

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。