作家
登录

了解jQuery技巧来提高你的代码

作者: 来源:www.28hudong.com 2013-03-30 01:57:26 阅读 我要评论

jQuery之所以如此流行并被从大公司到个人博客的几乎每个人都广泛使用,是因为它上手和使用相当简单,而且为我们提供了一些人都不知道的相当棒的特性。我认为jQuery的大多数用户更趋向于使用jQuery插件来解决面临的难题,这通常是明智的选择。但是当插件相对于你的需求有一定缺陷的时候,你也许更应该想办法自己来解决,下面来看看这些实用的jQuery技巧,他们肯定会能够派上用场的! 1.测试并提升你的jQuery选择器水平 这个jQuery选择器实验室非常酷,它能在线免费使用,当然你也能下来到本地离线使用。这个测试页面包含复杂的HTML组合字段,然后你能尝试预定义使用各种jQuery选择器。如果这还不够你也可以自定义选择器。 2.测试jQuery包装集是否包含某些元素 如果你想测试一下某个jQuery包装集中是否包含某些元素,你首先可以尝试使用验证首个元素是否存在: Code highlighting produced by Actipro CodeHighlighter (freeware) http://www.CodeHighlighter.com/ -->if($(selector)[0]){...}// 或者这样if($(selector).length){...} 来看看这个例子: Code highlighting produced by Actipro CodeHighlighter (freeware) http://www.CodeHighlighter.com/ -->//例子.如果你的页面有以下html代码<ul id="shopping_cart_items"> <li> <input class="in_stock" name="item" type="radio" value="Item-X" />Item X </li> <li> <input class="unknown" name="item" type="radio" value="Item-Y" />Item Y </li> <li> <input class="in_stock" name="item" type="radio" value="Item-Z" />Item Z </li></ul><pre escaped="true" lang="javascript">...//这个if条件将返回true,因为我们有两个input域匹配了选择器,所以<statement>代码将会执行if($('#shopping_cart_items input.in_stock')[0]){<statement>} 3.从jquery.org读取jQuery最新版本 你可以使用这句代码读取jQuery的最新版本的代码文件。 Code highlighting produced by Actipro CodeHighlighter (freeware) http://www.CodeHighlighter.com/ --><script src="http://code.jquery.com/jquery-latest.js"></script> 你可以使用这个方法来调用最近版本的jQuery框架,当然,你还可以使用下面这个代码从ajax.googleapis.com调用同样的最新版本jQuery: Code highlighting produced by Actipro CodeHighlighter (freeware) http://www.CodeHighlighter.com/ --><script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript"></script> 4.存储数据 使用data方法可以避免在DOM中存储数据,有些前端开发er喜欢使用HTML的属性来存储数据: Code highlighting produced by Actipro CodeHighlighter (freeware) http://www.CodeHighlighter.com/ -->$('selector').attr('alt', 'data being stored');//之后可以这样读取数据:$('selector').attr('alt'); 使用”alt”属性来作为参数名存储数据其实对于HTML来说是不符合语义的,我们可以使用jQuery的data方法来为页面中的某个元素存储数据: Code highlighting produced by Actipro CodeHighlighter (freeware) http://www.CodeHighlighter.com/ -->$('selector').data('参数名', '要存储的数据');//之后这样取得数据:$('selector').data('参数'); 这个data方法能让你自己明明数据的参数,更语义更灵活,你可以在页面上的任何元素存储数据信息。如果想了解更多关于data()和removeData()方法的介绍,可以看看jQuery官方讲解 这个方法的经典应用是给input域一个默认值,然后在聚焦的时候清空它: HTML部分: Code highlighting produced by Actipro CodeHighlighter (freeware) http://www.CodeHighlighter.com/ --><form id="testform"> <input type="text" class="clear" value="Always cleared" /> <input type="text" class="clear once" value="Cleared only once" /> <input type="text" value="Normal text" /></form> JavaSript部分: Code highlighting produced by Actipro CodeHighlighter (freeware) http://www.CodeHighlighter.com/ -->$( function() { // 取出有clear类的input域 // (注: "clear once" 是两个class: clear 和 once) $('#testform input.clear').each( function() { // 使用data方法存储数据 $(this).data("txt", $.trim($(this).val())); }).focus( function() { // 获得焦点时判断域内的值是否和默认值相同,如果相同则清空 if ($.trim($(this).val()) === $(this).data("txt")) { $(this).val(""); } }).blur( function() { // 为有class clear的域添加blur时间来恢复默认值 // 但如果class是once则忽略 if ($.trim($(this).val()) === "" && !$(this).hasClass("once")) { // Restore saved data $(this).val($(this).data("txt")); } });}); 查看Demo 5.jQuery手册常备身边 大多数人都很难记住所有的编程细节,即使再好的程序员也会有对某个程序语言的疏忽大意,所以把相关的手册打印出来或随时放在桌面上进行查阅绝对是可以提高编程效率的。 oscarotero jquery 1.3 (壁纸版) 6.在FireBug控制台记录jQuery FireBug是我最喜欢用的一个浏览器扩展工具之一,这个工具可以让你快速的在可视化界面中了解当前页面的HTML+CSS+JavaScript,并在该工具下完成即时开发。作为jQuery或JavaScript开发人员,FireFox对于记录你的JavaScript代码也得到支持。 写入FireBug控制台的最简单方式如下: console.log("hello world") 你也可以按照你希望的方式写一些参数: console.log(2,4,6,8,"foo",bar) 你也可以编写一个小扩展来记录jQuery对象到控制台: Code highlighting produced by Actipro CodeHighlighter (freeware) http://www.CodeHighlighter.com/ -->jQuery.fn.log = function(msg) { console.log("%s: %o", msg, this); return this;};// 对于这个扩展,你可以直接使用.log()方法来记录当前对象到控制台。$('#some_div').find('li.source > input:checkbox').log("sources to uncheck").removeAttr("checked"); 7.尽可能使用ID选择器 在使用jQuery之后,你会发现利用class属性来选择DOM元素变得相当简单。尽管如此,还是推荐大家尽量少用class选择器取而代之尽量多使用运行更快的ID选择器(IE浏览器下使用class选择器会在遍历整个DOM树之后返回相符的class包装集)。而ID选择器更快是因为 DOM本身就有”天然的”getElementById这个方法,而class并没有。所以如果使用class选择器的话,浏览器会遍历整个DOM,如果你的网页DOM结构足够复杂,这些class选择器足矣把页面拖得越来越慢。让我们看看这段简单的HTML代码: Code highlighting produced by Actipro CodeHighlighter (freeware) http://www.CodeHighlighter.com/ --><div id="main"> <form method="post" action="/"> <h2> Selectors in jQuery </h2> ... ... <input class="button" id="main_button" type="submit" value="Submit" /> </form></div> //使用class来调用submit按钮要比使用绝对的ID选择器慢很多 Code highlighting produced by Actipro CodeHighlighter (freeware) http://www.CodeHighlighter.com/ -->var main_button = $('#main .button');var main_button = $('#main_button'); 8.善于利用jQuery链 jQuery链不但允许以简洁的方式写出强大的操作,而且提高了开发效率,因为它能够把多个命令应用到包装集,而不必重新计算包装集。从而你不用再这样写了: Code highlighting produced by Actipro CodeHighlighter (freeware) http://www.CodeHighlighter.com/ --><li>Description: <input type="text" name="description" value="" /></li> Code highlighting produced by Actipro CodeHighlighter (freeware) http://www.CodeHighlighter.com/ -->$('#shopping_cart_items input.text').css('border', '3px dashed yellow');$('#shopping_cart_items input.text').css('background-color', 'red');$('#shopping_cart_items input.text').val("text updated"); 取而代之你可以使用jQuery链来完成简便的操作: Code highlighting produced by Actipro CodeHighlighter (freeware) http://www.CodeHighlighter.com/ -->var input_text = $('#shopping_cart_items input.text');input_text.css('border', '3px dashed yellow');input_text.css('background-color', 'red');input_text.val("text updated");// same with chaining:var input_text = $('#shopping_cart_items input.text');input_text.css('border', '3px dashed yellow').css('background-color', 'red').val("text updated"); 9.绑定jQuery函数到$(window).load事件 大多数jQuery实例或教程都告诉我们绑定我们的jQuery代码到$(document).ready事件。虽然$(document).ready事件在大多数情况下都OK,但是它的解析顺序是在文档准备就绪,单文档中的图片等对象正在下载的时候开始运行的。所以在某些时候使用$(document).ready事件并不一定能达到我们预期的效果,比如一些视觉效果和动画、拖拽、预读取隐藏图片等…通过使用$(window).load事件便可以安全的在整个文档都准备就绪之后再开始运行你期望的代码。 Code highlighting produced by Actipro CodeHighlighter (freeware) http://www.CodeHighlighter.com/ -->$(window).load( function() { // 将你希望在页面完全就绪之后运行的代码放在这里}); 10.使用jQuery链来限定选择器,让你的代码更简洁更优雅 由于JavaScript支持链结构而且支持断行,所以你的代码可以写成下面这样,这个例子先在元素上移除一个class然后在同一个元素上添加另一个class: Code highlighting produced by Actipro CodeHighlighter (freeware) http://www.CodeHighlighter.com/ -->$('#shopping_cart_items input.in_stock').removeClass('in_stock').addClass('3-5_days'); 如果想让它更简单实用,你可以创建一个支持链结构的jQuery函数: Code highlighting produced by Actipro CodeHighlighter (freeware) http://www.CodeHighlighter.com/ -->$.fn.makeNotInStock = function() { return $(this).removeClass('in_stock').addClass('3-5_days');}$('#shopping_cart_items input.in_stock').makeNotInStock().log(); 11.使用回调函数同步效果 如果你想确保某个事件或动画效果要在另一个事件运行之后再调用,那你就要使用回调函数了。你可以在这些动画效果后面绑定回调函数:slideDown( speed, [回调] ) ie. $(‘#sliding').slideDown('slow', function(){… 点击这里预览这个例子. Code highlighting produced by Actipro CodeHighlighter (freeware) http://www.CodeHighlighter.com/ --><style>div.button { background: #cfd; margin: 3px; width: 50px; text-align: center; float: left; cursor: pointer; border: 2px outset black; font-weight: bolder;}#sliding { display: none;}</style> Code highlighting produced by Actipro CodeHighlighter (freeware) http://www.CodeHighlighter.com/ -->$(document).ready( function() { // 使用jQuery的click事件改变视觉效果,并开启滑动效果 $("div.button").click( function() { // div.button 现在看上去是按下的效果 $(this).css( { borderStyle : "inset", cursor : "wait" }); // #sliding 现在将渐隐并在完成动作之后开启渐显效果 // slideup once it completes $('#sliding').slideDown('slow', function() { $('#sliding').slideUp('slow', function() { // 渐显效果完成后将会改变按钮的CSS属性 $('div.button').css( { borderStyle : "outset", cursor : "auto" }); }); }); });}); 12.学会使用自定义选择器 jQuery允许我们在css选择器的基础上定义自定义选择器来让我们的代码更简洁: Code highlighting produced by Actipro CodeHighlighter (freeware) http://www.CodeHighlighter.com/ -->$.expr[':' Code highlighting produced by Actipro CodeHighlighter (freeware) http://www.CodeHighlighter.com/ -->$.expr[':'].mycustomselector= function(element, index, meta, stack){ // element- DOM元素 // index - 堆栈中当前遍历的索引值 // meta - 关于你的选择器的数据元 // stack - 用于遍历所有元素的堆栈 // 包含当前元素则返回true // 不包含当前元素则返回false};// 自定义选择器的应用:$('.someClasses:test').doSomething();//下面让我们来看看一个小例子,我们通过使用自定义选择器来锁定含有”rel”属性的元素集:$.expr[':'].withRel = function(element){ var $this = $(element); // 仅返回rel属性不为空的元素 return ($this.attr('rel') != '');};$(document).ready(function(){ // 自定义选择器的使用很简单,它和其他选择器一样,返回一个元素包装集 // 你可以为他使用格式方法,比如下面这样修改它的css样式 $('a:withRel').css('background-color', 'green');}); Code highlighting produced by Actipro CodeHighlighter (freeware) http://www.CodeHighlighter.com/ --><ul> <li> <a href="#">without rel</a> </li> <li> <a rel="somerel" href="#">with rel</a> </li> <li> <a rel="" href="#">without rel</a> </li> <li> <a rel="nofollow" href="#">a link with rel</a> </li></ul> 13.预加载图片 通常使用JavaScript来预加载图片是个相当不错的方法: Code highlighting produced by Actipro CodeHighlighter (freeware) http://www.CodeHighlighter.com/ -->//定义预加载图片列表的函数(有参数)jQuery.preloadImages = function() { // 遍历图片 for ( var i = 0; i < arguments.length; i++) { jQuery("<img>").attr("src", arguments[i]); }}// 你可以这样使用预加载函数$.preloadImages("images/logo.png", "images/logo-face.png", "images/mission.png"); 14.将你的代码测试完好 jQuery有一个名为QUnit单元测试框架。编写测试很容易,它能让您可以放心地修改您的代码,并确保它仍然按预期工作。下面是如何工作的: Code highlighting produced by Actipro CodeHighlighter (freeware) http://www.CodeHighlighter.com/ -->//将测试分成若干模块.module("Module B");test("some other test", function() { // 指定多少个判断语句需要加入测试中. expect(2); equals(true, false, "failing test"); equals(true, true, "passing test");}); 英文原文:More jQuery and General Javascript Tips to Improve Your Code 翻译原文:http://blog.bingo929.com/jquery-javascript-tips-to-improve-code.html0,0,0)">].mycustomselector= function(element, index, meta, stack){ // element- DOM元素 // index - 堆栈中当前遍历的索引值 // meta - 关于你的选择器的数据元 // stack - 用于遍历所有元素的堆栈 // 包含当前元素则返回true // 不包含当前元素则返回false};// 自定义选择器的应用:$('.someClasses:test').doSomething();//下面让我们来看看一个小例子,我们通过使用自定义选择器来锁定含有”rel”属性的元素集:$.expr[':'].withRel = function(element){ var $this = $(element); // 仅返回rel属性不为空的元素 return ($this.attr('rel') != '');};$(document).ready(function(){ // 自定义选择器的使用很简单,它和其他选择器一样,返回一个元素包装集 // 你可以为他使用格式方法,比如下面这样修改它的css样式 $('a:withRel').css('background-color', 'green');}); Code highlighting produced by Actipro CodeHighlighter (freeware) http://www.CodeHighlighter.com/ --><ul> <li> <a href="#">without rel</a> </li> <li> <a rel="somerel" href="#">with rel</a> </li> <li> <a rel="" href="#">without rel</a> </li> <li> <a rel="nofollow" href="#">a link with rel</a> </li></ul> 13.预加载图片 通常使用JavaScript来预加载图片是个相当不错的方法: Code highlighting produced by Actipro CodeHighlighter (freeware) http://www.CodeHighlighter.com/ -->//定义预加载图片列表的函数(有参数)jQuery.preloadImages = function() { // 遍历图片 for ( var i = 0; i < arguments.length; i++) { jQuery("<img>").attr("src", arguments[i]); }}// 你可以这样使用预加载函数$.preloadImages("images/logo.png", "images/logo-face.png", "images/mission.png"); 14.将你的代码测试完好 jQuery有一个名为QUnit单元测试框架。编写测试很容易,它能让您可以放心地修改您的代码,并确保它仍然按预期工作。下面是如何工作的: Code highlighting produced by Actipro CodeHighlighter (freeware) http://www.CodeHighlighter.com/ -->//将测试分成若干模块.module("Module B");test("some other test", function() { // 指定多少个判断语句需要加入测试中. expect(2); equals(true, false, "failing test"); equals(true, true, "passing test");}); 英文原文:More jQuery and General Javascript Tips to Improve Your Code 翻译原文:http://blog.bingo929.com/jquery-javascript-tips-to-improve-code.html

  推荐阅读

  Javascript 中的类和闭包

有人说javascript也是面向对象的,只是它是prototype based,当然这只是概念上的区别,我不想讨论js是不是面向对象的,关键是想说明虽然javascript的类表现得很像其他语言中的类,但是内部的实现机理确不太一致,如>>>详细阅读


本文标题:了解jQuery技巧来提高你的代码

地址:http://www.17bianji.com/kaifa2/JS/27270.html

关键词: 探索发现

乐购科技部分新闻及文章转载自互联网,供读者交流和学习,若有涉及作者版权等问题请及时与我们联系,以便更正、删除或按规定办理。感谢所有提供资讯的网站,欢迎各类媒体与乐购科技进行文章共享合作。

网友点评
自媒体专栏

评论

热度

精彩导读
栏目ID=71的表不存在(操作类型=0)