`
lizaochengwen
  • 浏览: 643163 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

14条改善jQuery代码的技巧

 
阅读更多
<p><a href="http://paranimage.com/tag/jquery/">jquery</a>
简单易学,但如果你想写出更漂亮更简洁高效的代码,总需要一些技巧。本文就为你总结了<strong>14条改善jQuery代码的技巧</strong>
。</p>
<h3>1.测试并提升你的jQuery选择器水平</h3>
<p>这个<a href="http://codylindley.com/jqueryselectors/" target="_blank">jQuery选择器实验室</a>
非常酷,它能在线免费使用,当然你也能下来到本地离线使用。这个测试页面包含复杂的<a href="http://paranimage.com/category/dede/html/">html</a>
组合字段,然后你能尝试预定义使用各种jQuery选择器。如果这还不够你也可以自定义选择器。<br><img class="aligncenter size-full wp-image-11431" title="jquery-tips-01-500x280" src="http://paranimage.com/wp-content/uploads/2009/11/jquery-tips-01-500x280.jpg" alt="jquery tips 01 500x280 14条改善jQuery代码的技巧" width="500" height="280"></p>
<h3>2.测试jQuery包装集是否包含某些元素</h3>
<p>如果你想测试一下某个jQuery包装集中是否包含某些元素,你首先可以尝试使用验证首个元素是否存在:</p>
<pre><code class="javascript">

if($(selector)[0]){...}
// 或者这样
if($(selector).length){...}

</code>
</pre>
<p>来看看这个例子:</p>
<pre><code class="javascript">

//例子.如果你的页面有以下html代码
&lt;ul id="shopping_cart_items"&gt;
&lt;li&gt;&lt;input class="in_stock" name="item" type="radio" value="Item-X" /&gt;Item X&lt;/li&gt;
&lt;li&gt;&lt;input class="unknown" name="item" type="radio" value="Item-Y" /&gt;Item Y&lt;/li&gt;
&lt;li&gt;&lt;input class="in_stock" name="item" type="radio" value="Item-Z" /&gt;Item Z&lt;/li&gt;
&lt;/ul&gt;
&lt;pre escaped="true" lang="<a href="http://paranimage.com/category/dede/javascript/">javascript</a>
"&gt;...
//这个if条件将返回true,因为我们有两个
// input域匹配了选择器,所以&lt;statement&gt;代码将会执行
if($('#shopping_cart_items input.in_stock')[0]){&lt;statement&gt;}

</code>
</pre>
<h3>3.从jquery.org读取jQuery最新版本</h3>
<p>你可以使用这句代码读取jQuery的最新版本的代码文件。</p>
<pre><code class="javascript">

&lt;script src="http://code.jquery.com/jquery-latest.js"&gt;&lt;/script&gt;

</code>
</pre>
<p>你可以使用这个方法来调用最近版本的jQuery框架,当然,你还可以使用下面这个代码从<a href="http://paranimage.com/tag/ajax/">ajax</a>
.googleapis.com调用同样的最新版本jQuery:</p>
<pre><code class="javascript">

&lt;script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"
type="text/javascript"&gt;&lt;/script&gt;

</code>
</pre>
<h3>4.存储数据</h3>
<p>使用data方法可以避免在DOM中存储数据,有些前端开发er喜欢使用HTML的属性来存储数据:</p>
<pre><code class="javascript">

$('selector').attr('alt', 'data being stored');
//之后可以这样读取数据:
$('selector').attr('alt');

</code>
</pre>
<p>使用”alt”属性来作为参数名存储数据其实对于HTML来说是不符合语义的,我们可以使用jQuery的data方法来为页面中的某个元素存储数据:</p>
<pre><code class="javascript">

$('selector').data('参数名', '要存储的数据');
//之后这样取得数据:
$('selector').data('参数');

</code>
</pre>
<p>这个data方法能让你自己明明数据的参数,更语义更灵活,你可以在页面上的任何元素存储数据信息。如果想了解更多关于data()和removeData()方法的介绍,可以看看<a href="http://docs.jquery.com/Internals" target="_blank">jQuery官方讲解</a>
</p>
<p>这个方法的经典应用是给input域一个默认值,然后在聚焦的时候清空它:<br>
HTML部分:</p>
<pre><code class="html">

&lt;form id="testform"&gt;
&lt;input type="text" class="clear" value="Always cleared" /&gt;
&lt;input type="text" class="clear once" value="Cleared only once" /&gt;
&lt;input type="text" value="Normal text" /&gt;
&lt;/form&gt;

</code>
</pre>
<p>JavaSript部分:</p>
<pre><code class="javascript">

$(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()) === "" &amp;&amp; !$(this).hasClass("once") ) {
//Restore saved data
$(this).val( $(this).data("txt") );
}
});
});

</code>
</pre>
<p><a href="http://www.tripwiremagazine.com/wp-content/uploads/images/stories/Articles/jquery-tips/demo.html" target="_blank">查看Demo</a>
</p>
<h3>5.jQuery手册常备身边</h3>
<p>大多数人都很难记住所有的编程细节,即使再好的程序员也会有对某个程序语言的疏忽大意,所以把相关的手册打印出来或随时放在桌面上进行查阅绝对是可以提高编程效率的。<br><a href="http://oscarotero.com/jquery/" target="_blank">oscarotero jquery 1.3</a>
(<a href="http://www.gmtaz.com/index.php/jquery-13-cheatsheet-wallpaper/" target="_blank">壁纸版</a>
)</p>
<p><img class="aligncenter size-full wp-image-11432" title="oscarotero" src="http://paranimage.com/wp-content/uploads/2009/11/oscarotero.jpg" alt="oscarotero 14条改善jQuery代码的技巧" width="471" height="348"></p>
<h3>6.在FireBug控制台记录jQuery</h3>
<p>FireBug是我最喜欢用的一个浏览器扩展工具之一,这个工具可以让你快速的在可视化界面中了解当前页面的HTML+<a href="http://paranimage.com/category/dede/css/">CSS</a>
+JavaScript,并在该工具下完成即时开发。作为jQuery或JavaScript开发人员,<a href="http://paranimage.com/category/apps/firefox/">firefox</a>
对于<a href="http://www.getfirebug.com/logging.html" target="_blank">记录你的JavaScript代码</a>
也得到支持。</p>
<p>写入FireBug控制台的最简单方式如下:</p>
<pre><code class="javascript">

console.log("hello world")

<img class="aligncenter size-full wp-image-11433" title="fire-500x200" src="http://paranimage.com/wp-content/uploads/2009/11/fire-500x200.jpg" alt="fire 500x200 14条改善jQuery代码的技巧" width="500" height="200"></code>
</pre>
<p>你也可以按照你希望的方式写一些参数:</p>
<pre><code class="javascript">

console.log(2,4,6,8,"foo",bar)

</code>
</pre>
<p>你也可以编写一个小扩展来记录jQuery对象到控制台:</p>
<pre><code class="javascript">

jQuery.fn.log = function (msg) {
console.log("%s: %o", msg, this);
return this;
};

</code>
</pre>
<p>对于这个扩展,你可以直接使用.log()方法来记录当前对象到控制台。</p>
<pre><code class="javascript">

$('#some_div').find('li.source &gt; input:checkbox')
.log("sources to uncheck")
.removeAttr("checked");

</code>
</pre>
<h3>7.尽可能使用ID选择器</h3>
<p>在使用jQuery之后,你会发现利用class属性来选择DOM元素变得相当简单。尽管如此,还是推荐大家尽量少用class选择器取而代之
尽量多使用运行更快的ID选择器(IE浏览器下使用class选择器会在遍历整个DOM树之后返回相符的class包装集)。而ID选择器更快是因为
DOM本身就有”天然的”getElementById这个方法,而class并没有。所以如果使用class选择器的话,浏览器会遍历整个DOM,如果
你的网页DOM结构足够复杂,这些class选择器足矣把页面拖得越来越慢。让我们看看这段简单的HTML代码:</p>
<pre><code class="html">

&lt;div id="main"&gt;
&lt;form method="post" action="/"&gt;
&lt;h2&gt;Selectors in jQuery&lt;/h2&gt;
...
...
&lt;input class="button" id="main_button" type="submit" value="Submit" /&gt;
&lt;/form&gt;
&lt;/div&gt;

</code>
</pre>
<pre><code class="javascript">

//使用class来调用submit按钮要比使用绝对的ID选择器慢很多
var main_button = $('#main .button');
var main_button = $('#main_button');

</code>
</pre>
<h3>8.善于利用jQuery链</h3>
<p>jQuery链不但允许以简洁的方式写出强大的操作,而且提高了开发效率,因为它能够把多个命令应用到包装集,而不必重新计算包装集。从而你不用再这样写了:</p>
<pre><code class="html">

&lt;li&gt;Description: &lt;input type="text" name="description" value="" /&gt;&lt;/li&gt;

</code>
</pre>
<pre><code class="javascript">

$('#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");

</code>
</pre>
<p>取而代之你可以使用jQuery链来完成简便的操作:</p>
<pre><code class="javascript">

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");

</code>
</pre>
<h3>9.绑定jQuery函数到$(window).load事件</h3>
<p>大多数jQuery实例或教程都告诉我们绑定我们的jQuery代码到$(document).ready事件。虽
然$(document).ready事件在大多数情况下都OK,但是它的解析顺序是在文档准备就绪,单文档中的图片等对象正在下载的时候开始运行的。所
以在某些时候使用$(document).ready事件并不一定能达到我们预期的效果,比如一些视觉效果和动画、拖拽、预读取隐藏图片等…通过使
用$(window).load事件便可以安全的在整个文档都准备就绪之后再开始运行你期望的代码。</p>
<pre><code class="javascript">

$(window).load(function(){
// 将你希望在页面完全就绪之后运行的代码放在这里
});

</code>
</pre>
<h3>10.使用jQuery链来限定选择器,让你的代码更简洁更优雅</h3>
<p>由于JavaScript支持链结构而且支持断行,所以你的代码可以写成下面这样,这个例子先在元素上移除一个class然后在同一个元素上添加另一个class:</p>
<pre><code class="javascript">

$('#shopping_cart_items input.in_stock')
.removeClass('in_stock')
.addClass('3-5_days');

</code>
</pre>
<p>如果想让它更简单实用,你可以创建一个支持链结构的jQuery函数:</p>
<pre><code class="javascript">

$.fn.makeNotInStock = function() {
return $(this).removeClass('in_stock').addClass('3-5_days');
}

$('#shopping_cart_items input.in_stock').makeNotInStock().log();

</code>
</pre>
<h3>11.使用回调函数同步效果</h3>
<p>如果你想确保某个事件或动画效果要在另一个事件运行之后再调用,那你就要使用回调函数了。你可以在这些动画效果后面绑定回调函
数:slideDown( speed, [回调] ) ie. $(’#sliding’).slideDown(’slow’,
function(){… <a href="http://www.tripwiremagazine.com/wp-content/uploads/images/stories/Articles/jquery-tips2/demo.html" target="_blank">点击这里</a>
预览这个例子.</p>
<pre><code class="css">

&lt;style&gt;
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; }
&lt;/style&gt;

</code>
</pre>
<pre><code class="javascript">

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

</code>
</pre>
<h3>12.学会使用自定义选择器</h3>
<p>jQuery允许我们在css选择器的基础上定义自定义选择器来让我们的代码更简洁:</p>
<pre><code class="javascript">

$.expr[':'].mycustomselector= function(element, index, meta, stack){
// element- DOM元素
// index - 堆栈中当前遍历的索引值
// meta - 关于你的选择器的数据元
// stack - 用于遍历所有元素的堆栈

// 包含当前元素则返回true
// 不包含当前元素则返回false
};

// 自定义选择器的应用:
$('.someClasses:test').doSomething();

</code>
</pre>
<p>下面让我们来看看一个小例子,我们通过使用自定义选择器来锁定含有”rel”属性的元素集:</p>
<pre><code class="javascript">

$.expr[':'].withRel = function(element){
var $this = $(element);
//仅返回rel属性不为空的元素
return ($this.attr('rel') != '');
};

$(document).ready(function(){
//自定义选择器的使用很简单,它和其他选择器一样,返回一个元素包装集
//你可以为他使用格式方法,比如下面这样修改它的css样式
$('a:withRel').css('background-color', 'green');
});

</code>
</pre>
<pre><code class="html">

&lt;ul&gt;
&lt;li&gt;
&lt;a href="#"&gt;without rel&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;a rel="somerel" href="#"&gt;with rel&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;a rel="" href="#"&gt;without rel&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;a rel="nofollow" href="#"&gt;a link with rel&lt;/a&gt;
&lt;/li&gt;
&lt;/ul&gt;

</code>
</pre>
<h3>13.预加载图片</h3>
<p>通常使用JavaScript来预加载图片是个相当不错的方法:</p>
<pre><code class="javascript">

//定义预加载图片列表的函数(有参数)

jQuery.preloadImages = function(){
//遍历图片
for(var i = 0; i&lt;arguments.length; i++){
jQuery("&lt;img&gt;").attr("src", arguments[i]);

}
}
// 你可以这样使用预加载函数
$.preloadImages("images/logo.png", "images/logo-face.png", "images/mission.png");

</code>
</pre>
<h3>14.将你的代码测试完好</h3>
<p>jQuery有一个名为QUnit单元测试框架。编写测试很容易,它能让您可以放心地修改您的代码,并确保它仍然按预期工作。下面是如何工作的:</p>
<pre><code class="javascript">

//将测试分成若干模块.
module("Module B");

test("some other test", function() {
//指定多少个判断语句需要加入测试中.
expect(2);

equals( true, false, "failing test" );
equals( true, true, "passing test" );
});

</code>
</pre>
<p>英文原文:<a title="More jQuery and General Javascript Tips to Improve Your Code" href="http://www.tripwiremagazine.com/ajax/developer-toolbox/more-jquery-and-general-javascript-tips-to-improve-your-code.html" target="_blank">More jQuery and General Javascript Tips to Improve Your Code</a>
<br>
中文译文:<a title="了解更多jQuery技巧来提高你的代码" href="http://blog.bingo929.com/jquery-javascript-tips-to-improve-code.html">了解更多jQuery技巧来提高你的代码/彬GO</a>
</p>
<p>来源于 <a title="14条改善jQuery代码的技巧" rel="bookmark" href="http://paranimage.com/14-tips-to-improve-jquery-code/">14条改善jQuery代码的技巧 | 帕兰映像</a>
</p>
<p class="tags">标签: <a rel="tag" href="http://paranimage.com/tag/javascript/">JavaScript</a>
, <a rel="tag" href="http://paranimage.com/tag/jquery/">jquery<br></a>
</p>
<p><ins style="display: inline-table; border: none; height: 280px; margin: 0; padding: 0; width: 336px;"><ins id="aswift_0_anchor" style="display: block; border: none; height: 280px; margin: 0; padding: 0; width: 336px;">作者:帕克<br></ins>
</ins>
<span class="post-author" style="padding: 0pt 0pt 10px;"><a title="由 帕兰 发布" rel="author" href="http://paranimage.com/author/admin/"></a>
</span>
</p>
<div class="post-meta">

</div>
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics