﻿<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>礁湖星云 &#187; 插件</title>
	<atom:link href="http://www.icyfire.me/tag/%e6%8f%92%e4%bb%b6/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.icyfire.me</link>
	<description>太阳底下没有新鲜事。</description>
	<lastBuildDate>Tue, 31 Jan 2012 02:50:19 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>[jQuery]怎样开发一个jQuery插件</title>
		<link>http://www.icyfire.me/2009/10/how-to-develop-a-jquery-plugin/</link>
		<comments>http://www.icyfire.me/2009/10/how-to-develop-a-jquery-plugin/#comments</comments>
		<pubDate>Wed, 28 Oct 2009 15:35:00 +0000</pubDate>
		<dc:creator>icyfire</dc:creator>
				<category><![CDATA[网站前端]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[插件]]></category>

		<guid isPermaLink="false">http://www.icyfire.me/?p=882</guid>
		<description><![CDATA[<img src="http://www.icyfire.me/wp-content/uploads/2009/10/114-jquery-plugin.jpg" alt="" />

<a href="http://jquery.com/" target="_blank">jQuery</a>是当前最为流行的JavaScript库，许多网站使用它来实现一些动态效果和Ajax功能。然而，很少的开发者会深入去研究插件的开发。

在这篇教程里，我们将会创建一个简单的插件来解释一些基础。这个插件的作用是将一个或者多个选择的节点的文本翻转。

<b>Translated by icyfire @ Canaand on Wed, 28th Oct.</b>
<font color="#ffffff">看得懂代表你理解能力强，看不懂代表我翻译能力烂……</font> <a href="http://www.icyfire.me/2009/10/how-to-develop-a-jquery-plugin/">继续阅读 <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p><a href="http://jquery.com/" target="_blank">jQuery</a>是当前最为流行的JavaScript库，许多网站使用它来实现一些动态效果和Ajax功能。然而，很少的开发者会深入去研究插件的开发。</p>
<p>在这篇教程里，我们将会创建一个简单的插件来解释一些基础。这个插件的作用是将一个或者多个选择的节点的文本翻转（<a href="http://blogs.sitepointstatic.com/examples/tech/jquery-plugin/index.html" target="_blank">示例页面</a>）。</p>
<h2 style="color:#003366;">为什么要创建jQuery插件？</h2>
<p>总而言之，一个词：重用。通过扩展jQuery，你可以创建一个可以在其他任何网页上使用的可重用组件。你的代码会被封装起来，减少了在其他地方函数名冲突的风险。</p>
<h2 style="color:#003366;">jQuery的工作原理</h2>
<p>jQuery传递DOM元素或者一个包含CSS选择器的字符串到其核心函数，然后返回一个jQuery对象，这个对象是一个类似数组的DOM节点集合。这些节点关联了一个或者多个的方法。例如：</p>
<pre class="brush: javascript; gutter: true">
// color all &lt;p&gt; tags red
$("p").css("color", "red");
</pre>
<p>注意：虽然jQuery库的名字是"jQuery"，但是它提供了一个快捷的变量"$"来引用它。需要注意的是，其他的JS库也有可能会使用"$"。</p>
<h2 style="color:#003366;">jQuery插件的工作原理</h2>
<p>jQuery允许添加方法到它的库里。当这些方法被调用的时候，jQuery对象会被传递过去。DOM节点可以根据需要随意操作，同时方法应该返回"this"以便链式调用其他的方法。</p>
<p>我们的示例插件会以以下的形式调用：</p>
<pre class="brush: javascript; gutter: true">
// reverse the text in all &lt;p&gt; tags
$("p").reverseText();
</pre>
<p>我们还会增加两个可选的参数，minlenght和maxlength。当这两个参数被使用的时候，字符串的长度必须在这两个参数的值之间翻转才会发生。</p>
<h2 style="color:#003366;">插件的声明</h2>
<p>插件的定义使用到了jQuery的fn方法，例如：</p>
<pre class="brush: javascript; gutter: true">
jQuery.fn.reverseText = function(params) { ... };
</pre>
<p>之所以使用"jQuery"而不是"$"是想确保不会跟其他的JS库冲突。我们所有的内部代码也都应该这样。但是，我们可以通过使用匿名方法（anonymous function）来帮我们少打几个字和减少文件的大小：</p>
<pre class="brush: javascript; gutter: true">
(function($) {
	$.fn.reverseText = function(params) { ... };
})(jQuery);
</pre>
<p>这个函数会立刻被执行，它传递jQuery作为一个命名为"$"的参数。因为"$"是局部变量，所以我们可以假定它一直作为jQuery的引用而不是其他库的一个全局变量。</p>
<h2 style="color:#003366;">插件参数</h2>
<p>我们为我们的插件设置两个参数：minlength和maxlenght。最简单的方法是把它们作为函数的变量，例如：</p>
<pre class="brush: javascript; gutter: true">
(function($) {
	$.fn.reverseText = function(minlength, maxlength) { ... };
})(jQuery);

// example
$("p").reverseText(0, 100);
</pre>
<p>但是如果我们之后想增加参数呢？我们的插件可能会有很多的选项，变量处理在这种情况下很快就会变得复杂。作为一个替代方案，我们可以传递一个JSON对象给方法：</p>
<pre class="brush: javascript; gutter: true">
(function($) {
	$.fn.reverseText = function(params) { ... }
})(jQuery);

// example
$("p").reverseText( { minlength: 0, maxlength: 100 } );
</pre>
<p>reverseText函数的第一行应该定义一组默认参数，用户可以自定义这些参数的值去覆盖它们。jQuery的extend函数可以帮我们实现：</p>
<pre class="brush: javascript; gutter: true">
// merge default and user parameters
params = $.extend( {minlength: 0, maxlength: 99999}, params);
</pre>
<p>这里，<strong>params.minlength</strong>等于0，而<strong>params.maxlength</strong>等于99999，直到调用时被新的值覆盖。</p>
<h2 style="color:#003366;">插件代码</h2>
<p>我们可以开始写我们的主要代码了：</p>
<pre class="brush: javascript; gutter: true">
// traverse all nodes
this.each(function() {

	// express a single node as a jQuery object
	var $t = $(this);

	// find text
	var origText = $t.text(), newText = '';

	// text length within defined limits?
	if (origText.length >= params.minlength &#038;&  origText.length <= params.maxlength) {

		// reverse text
		for (var i = origText.length-1; i >= 0; i--) newText += origText.substr(i, 1);
		$t.text(newText);

	}

});
</pre>
<p>解释：</p>
<ul>
<li>方法this.each遍历了所有的jQuery DOM节点，并调用了一个匿名函数。</li>
<li>在这个匿名函数里，'this'代表了一个节点。我们把这个jQuery的节点集合赋值予$t，这样我们就能使用jQuery的方法了。</li>
<li>变量origText被赋予了节点的文本值，而变量newText则被设为一个空的字符串。</li>
<li>如果origText的长度介于params.minlength和params.maxlength之间，那么通过一个循环，我们把它的值进行了翻转。然后，我们相应的更新了DOM节点的文本值。</li>
</ul>
<h2 style="color:#003366;">别破坏连锁！</h2>
<p>最后，切记要返回一个jQuery对象，这样其他方法可以进行链式调用了：</p>
<pre class="brush: javascript; gutter: true">
return this;
</pre>
<h2 style="color:#003366;">完整的代码</h2>
<p>我们的插件代码终于完成了：</p>
<pre class="brush: javascript; gutter: true">
(function($) {

    // jQuery plugin definition
    $.fn.reverseText = function(params) {

	// merge default and user parameters
	params = $.extend( {minlength: 0, maxlength: 99999}, params);

	// traverse all nodes
	this.each(function() {

	    // express a single node as a jQuery object
	    var $t = $(this);

	    // find text
	    var origText = $t.text(), newText = '';

	    // text length within defined limits?
	    if (origText.length >= params.minlength &#038;&  origText.length <= params.maxlength) {

		// reverse text
		for (var i = origText.length-1; i >= 0; i--) newText += origText.substr(i, 1);
		    $t.text(newText);

	    }

	});

	// allow jQuery chaining
	return this;
    };

})(jQuery);
</pre>
<p>文件保存为：jquery.reversetext.js。之后在HTML页面里我们可以在加载jQuery后引入它：</p>
<pre class="brush: html; gutter: true">
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
<head>

</head>
<body>
<h1>jQuery plugin: reverseText</h1>

This jQuery plugin reverses all the text in the selected nodes.
<ul>
<li>This text will be reversed</li>
<li>This text will not be reversed</li>
<li>reversed</li>
<li>not reversed</li>
</ul>

<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="jquery.reversetext.js"></script>
<script type="text/javascript">
// reverse even-numbered LI tag text
$("ul li:even").reverseText();
</script>

</body>
</html>
</pre>
<p>现在这个页面的list的第一行和第三行都被翻转了（记住，第一项是从0开始）：<br />
<img src="http://www.icyfire.me/wp-content/uploads/2009/10/114-jquery-plugin-example.png" alt="" /><br />
<strong>资源：</strong></p>
<ul>
<li><a href="http://blogs.sitepointstatic.com/examples/tech/jquery-plugin/index.html" target="_blank"><strong>查看插件示例页面</strong></a></li>
<li><a href="http://blogs.sitepointstatic.com/examples/tech/jquery-plugin/jquery.reversetext.js" target="_blank">查看插件代码</a></li>
<li><a href="http://blogs.sitepointstatic.com/examples/tech/jquery-plugin/jquery.reversetext.zip" target="_blank">现在插件和实例代码</a></li>
</ul>
<p>现在你应该对jQuery插件开发有不错的了解了。<a href="http://www.sitepoint.com/forums//forumdisplay.php?f=15" target="_blank">SitePoint JavaScript forum</a>也是一个学习的好地方。</p>
<p><strong>Translated by icyfire @ Canaand on Wed, 28th Oct.</strong></p>
<p>作者：<a href="http://www.sitepoint.com/articlelist/560">Craig Buckler</a><br />
原文：<a href="http://www.sitepoint.com/blogs/2009/07/22/how-to-develop-a-jquery-plugin/">How To Develop a jQuery Plugin</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.icyfire.me/2009/10/how-to-develop-a-jquery-plugin/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

