Chinaunix首页 | 论坛 | 博客
  • 博客访问: 869235
  • 博文数量: 322
  • 博客积分: 6688
  • 博客等级: 准将
  • 技术积分: 3626
  • 用 户 组: 普通用户
  • 注册时间: 2010-09-19 11:26
文章分类

全部博文(322)

文章存档

2013年(5)

2012年(66)

2011年(87)

2010年(164)

分类: 系统运维

2011-09-07 17:24:08

今天的帖子会给你们展示50个jquery代码片段,这些代码能够给你的javascript项目提供帮助。其中的一些代码段是从jQuery1.4.2才开始支持的做法,另一些则是真正有用的函数或方法,他们能够帮助你又快又好地把事情完成。我希望你在这一文章中能找到有帮助的东西。
上一篇:50个jQuery代码段帮你成为更好的JavaScript开发者(上)

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

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 //这段代码展示了在用户未输入值时, //如何在文本类型的input域中保留 //一个默认值 wap_val = []; $(".swap").each(function(i){ wap_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]); } }); });
1 type="text" value="Enter Username here.." class="swap" />

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

1 2 3 4 5 6 //这是1.3.2中我们使用setTimeout来实现的方式 setTimeout(function() { $('.mydiv').hide('blind', {}, 500) }, 5000); //而这是在1.4中可以使用delay()这一功能来实现的方式(这很像是休眠) $(".mydiv").delay(5000).hide('blind', {}, 500);

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

1 2 var newDiv = $(''); newDiv.attr('id','myNewDiv').appendTo('body');

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

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 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"){ //Apply the standard maxLength 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); } }; } }); }; //用法 $('#mytextarea').maxLength(500);

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

1 2 3 4 5 6 7 8 9 //把测试单独放在模块中 module("Module B"); test("some other test", function() { //指明测试内部预期有多少要运行的断言 expect(2); //一个比较断言,相当于JUnit的assertEquals equals( true, false, "failing test" ); equals( true, true, "passing test" ); });

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

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

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

1 2 3 if($(element).is(':visible') == 'true') { //该元素是可见的 }

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

1 2 3 4 5 6 7 8 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();

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

1 2 3 4 var arrInputValues = new Array(); $("input[name='table[]']").each(function(){ arrInputValues.push($(this).val()); });

35. 如何从元素中除去html

1 2 3 4 5 6 7 8 9 10 11 (function($) { $.fn.stripHtml = function() { var regexp = /<("[^"]*"|'[^']*'|[^'">])*>/gi; this.each(function() { $(this).html( $(this).html().replace(regexp,") ); }); return $(this); } })(jQuery); //用法: $('p').stripHtml();

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

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

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

1 2 3 4 5 6 7 8 9 // 允许链式日志记录 // 用法: $('#someDiv').hide().log('div hidden').addClass('someClass'); jQuery.log = jQuery.fn.log = function (msg) { if (console){ console.log("%s: %o", msg, this); } return this; };

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

1 2 3 4 5 6 7 jQuery('a.popup').live('click', function(){ newwindow=window.open($(this).attr('href'),'','height=200,width=150'); if (window.focus) { newwindow.focus(); } return false; });

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

1 2 3 4 5 jQuery('a.newTab').live('click', function(){ newwindow=window.open($(this).href); jQuery(this).target = "_blank"; return false; });

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

1 2 3 4 5 6 7 8 9 // 不这样做 $('#nav li').click(function(){ $('#nav li').removeClass('active'); $(this).addClass('active'); }); //替代做法是 $('#nav li').click(function(){ $(this).addClass('active').siblings().removeClass('active'); });

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

1 2 3 4 5 6 var tog = false; // 或者为true,如果它们在加载时为被选中状态的话 $('a').click(function() { $("input[type=checkbox]").attr("checked",!tog); tog = !tog; });

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

1 2 3 4 5 //如果元素的值和输入的文本相匹配的话 //该元素将被返回 $('.someClass').filter(function() { return $(this).attr('value') == $('input#someId').val(); })

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

1 2 3 4 5 $(document).ready(function() { $(document).mousemove(function(e){ $(’#XY’).html(”X Axis :+ e.pageX +| Y Axis ” + e.pageY); }); });

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

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

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

1 2 3 4 5 6 function par***ml(xml) { //找到每个Tutorial并打印出author $(xml).find("Tutorial").each(function() { $("#output").append($(this).attr("author") + ""); }); }

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

1 2 3 $('#theImage').attr('src', 'image.jpg').load(function() { alert('This Image Has Been Loaded'); });

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

1 2 3 4 5 6 //事件可以这样绑定命名空间 $('input').bind('blur.validation', function(e){ // ... }); //data方法也接受命名空间 $('input').data('validation.isValid', true);

48. 如何检查cookie是否启用

1 2 3 4 5 6 7 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) { //没有启用cookie }

49. 如何让cookie过期:

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

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

1 2 3 4 5 6 7 8 9 10 11 $.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,'$1‘) ); }); return $(this); } //用法  $('p').replaceUrl();

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

阅读(812) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~