<?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>haojii &#187; jQuery</title>
	<atom:link href="http://www.haojii.com/tag/jquery/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.haojii.com</link>
	<description>一个专注于技术的IT男</description>
	<lastBuildDate>Thu, 19 Apr 2012 07:58:49 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
		<item>
		<title>自定义input type=”file”的样式以及引出的相关技术问题</title>
		<link>http://www.haojii.com/2011/04/jquery-change-event-to-input-file-on-ie/</link>
		<comments>http://www.haojii.com/2011/04/jquery-change-event-to-input-file-on-ie/#comments</comments>
		<pubDate>Fri, 29 Apr 2011 06:58:57 +0000</pubDate>
		<dc:creator>Jacky</dc:creator>
				<category><![CDATA[CSS]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[自定义input type=file样式]]></category>

		<guid isPermaLink="false">http://www.haojii.com/?p=552</guid>
		<description><![CDATA[因为不同浏览器下如果使用默认的input type=”file”元素，效果如下 为了保证不同浏览器下的UI一致我们有需求要自定义input type=”file”元素的样式 如何Style input type=”file”元素的相关长篇讨论 1. Styling an input type=”file” http://www.quirksmode.org/dom/inputfile.html 2. Howto Style the Button of a input type=”file” Control http://imar.spaanjaars.com/154/howto-style-the-button-of-a-input-typefile-control 翻译成白话文就是 1. 隐藏input type=”file” 2. 用CSS将a+span做成按钮样式，对其做事件绑定，点击之后触发input type=”file”的点击事件 3. 用input type=”text”显示input type=”file”选中文件的值 查看能工作的live code http://jsfiddle.net/jihao/sFCQV/ HTML CSS &#8230; <a href="http://www.haojii.com/2011/04/jquery-change-event-to-input-file-on-ie/">继续阅读 <span class="meta-nav">&#8594;</span></a><table class="wumii-related-items" cellspacing="0" cellpadding="2" border="0" width="100%" style="clear: both;">
    
    <tr>
        <td ><b><font size="-1" color="#FF0000" style="display: block !important; padding: 20px 0 5px !important;">其他文章：</font></b></td>
    </tr>
    
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect?url=http%3A%2F%2Fwww.haojii.com%2F2010%2F04%2F20-helpful-jquery-methods-you-should-be-using%2F&from=http%3A%2F%2Fwww.haojii.com%2F2011%2F04%2Fjquery-change-event-to-input-file-on-ie%2F">
                        <font size="-1" color="#667FFA" style="line-height: 1.65em; font-size: 12px !important;">你应该使用的20个有用的jQuery方法</font>
                    </a>
                </td>
            </tr>
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect?url=http%3A%2F%2Fwww.haojii.com%2F2010%2F01%2Fworking-with-events-part-3-more-event-delegation-with-jquery%2F&from=http%3A%2F%2Fwww.haojii.com%2F2011%2F04%2Fjquery-change-event-to-input-file-on-ie%2F">
                        <font size="-1" color="#667FFA" style="line-height: 1.65em; font-size: 12px !important;">Working with Events, Part 3: More Event Delegation with jQuery</font>
                    </a>
                </td>
            </tr>
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect?url=http%3A%2F%2Fwww.haojii.com%2F2010%2F05%2Fcool-demo-with-jquery-plugin-fancybox%2F&from=http%3A%2F%2Fwww.haojii.com%2F2011%2F04%2Fjquery-change-event-to-input-file-on-ie%2F">
                        <font size="-1" color="#667FFA" style="line-height: 1.65em; font-size: 12px !important;">Cool demo with jQuery plugin FancyBox</font>
                    </a>
                </td>
            </tr>
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect?url=http%3A%2F%2Fwww.haojii.com%2F2010%2F01%2Fjquery-1-4-released-the-15-new-features-you-must-know%2F&from=http%3A%2F%2Fwww.haojii.com%2F2011%2F04%2Fjquery-change-event-to-input-file-on-ie%2F">
                        <font size="-1" color="#667FFA" style="line-height: 1.65em; font-size: 12px !important;">jQuery1.4发布: 你必须知道的15个新特性</font>
                    </a>
                </td>
            </tr>
    
    <tr>
        <td  align="right">
            <a style="text-decoration: none !important;" href="http://www.wumii.com/widget/relatedItems" target="_blank" title="无觅相关文章插件">
                <font size="-1" color="#bbbbbb" style="display: block !important; font-family: arial !important; padding: 5px 0 !important; font-size: 12px !important; color: #bbb !important;">无觅</font>
            </a>
        </td>
    </tr>
</table>]]></description>
			<content:encoded><![CDATA[<p>因为不同浏览器下如果使用默认的input type=”file”元素，效果如下</p>
<p><a rel="attachment wp-att-553" href="http://www.haojii.com/2011/04/jquery-change-event-to-input-file-on-ie/filefields/"><img class="aligncenter size-full wp-image-553" title="filefields" src="http://www.haojii.com/blog/wp-content/uploads/filefields.gif" alt="" width="381" height="225" /></a></p>
<p>为了保证不同浏览器下的UI一致我们有需求要自定义input type=”file”元素的样式</p>
<p>如何Style input type=”file”元素的相关长篇讨论<br />
1. Styling an input type=”file”<br />
<a href="http://www.quirksmode.org/dom/inputfile.html">http://www.quirksmode.org/dom/inputfile.html</a></p>
<p>2. Howto Style the Button of a input type=”file” Control<br />
<a href="http://imar.spaanjaars.com/154/howto-style-the-button-of-a-input-typefile-control">http://imar.spaanjaars.com/154/howto-style-the-button-of-a-input-typefile-control</a></p>
<p>翻译成白话文就是<br />
1. 隐藏input type=”file”<br />
2. 用CSS将a+span做成按钮样式，对其做事件绑定，点击之后触发input type=”file”的点击事件<br />
3. 用input type=”text”显示input type=”file”选中文件的值</p>
<p>查看能工作的live code<br />
<a href="http://jsfiddle.net/jihao/sFCQV/">http://jsfiddle.net/jihao/sFCQV/</a></p>
<p>HTML</p>
<pre class="brush: xml; title: ; notranslate">
&lt;input type=&quot;text&quot; id=&quot;fakeFile&quot; name=&quot;fakeFile&quot;&gt;

&lt;a class=&quot;linkButton&quot; id=&quot;link_browse&quot; href=&quot;#&quot;&gt;&lt;span&gt;Link Button BROWSE&lt;/span&gt;&lt;/a&gt;

&lt;input id=&quot;theFile&quot; type=&quot;file&quot;
  style=&quot;visibility:hidden;opacity:0;cursor:pointer;*filter: alpha(opacity=0);&quot;&gt;
</pre>
<p>CSS</p>
<pre class="brush: css; title: ; notranslate">
a.linkButton{
    background: #332233;/*style this link to look like a button*/
    color: #FFFFFF;
    padding: 0 0 0 10px;
    text-decoration: none;
}
a.linkButton&gt;span{
    padding: 0 10px 0 0;
}
</pre>
<p>JavaScript</p>
<pre class="brush: jscript; title: ; notranslate">
$(function() {
    $('#browse,#link_browse').click(function(event) {
        event.preventDefault();
        $('#theFile').trigger('click');
    });

    function changeCallBack() {
        $('#fakeFile').val($('#theFile').val());
    };

    //this works for FF, easy job
    $('#theFile').bind('change', function() {
        alert('gotcha!');
        changeCallBack();

    });
});
</pre>
<p>写完这段代码之后遇到的相关问题<br />
问题1. FireFox下不会显示文件全路径（google得知这是FF的安全考虑，不影响form提交）<br />
问题2. IE下选择文件后不会触发change事件，原因是IE处理打开文件的机制（参考下面的链接看更多讨论）<br />
对于IE8，这个问题的解决办法如下，setTimeout会阻塞，直到文件选择器关闭之后，回调函数才被调用（更新用来显示的input type=”text”的值）</p>
<pre class="brush: jscript; title: ; notranslate">
    if ($.browser.msie) {
        $('#theFile').bind('click', function() {
            //this solution works for IE8, not Maxthon2, so seems not IE6 either(not tested)
            setTimeout(function() {
                alert('[IE8] setTimeout get called after open file dialog was closed');
                changeCallBack();
            }, 0);

        });
    }
</pre>
<p>查看能工作的live code<br />
<a href="http://jsfiddle.net/jihao/sFCQV/">http://jsfiddle.net/jihao/sFCQV/</a></p>
<p>关于IE change事件的相关讨论<br />
1. jQuery, .change() notification, and IE （关于radio button的change事件绑定）<br />
<a href="http://norman.walsh.name/2009/03/24/jQueryIE">http://norman.walsh.name/2009/03/24/jQueryIE</a></p>
<p>2. jQuery: change event to input file on IE<br />
<a href="http://stackoverflow.com/questions/2389341/jquery-change-event-to-input-file-on-ie">http://stackoverflow.com/questions/2389341/jquery-change-event-to-input-file-on-ie</a></p>
<table class="wumii-related-items" cellspacing="0" cellpadding="2" border="0" width="100%" style="clear: both;">
    
    <tr>
        <td ><b><font size="-1" color="#FF0000" style="display: block !important; padding: 20px 0 5px !important;">其他文章：</font></b></td>
    </tr>
    
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect?url=http%3A%2F%2Fwww.haojii.com%2F2010%2F04%2F20-helpful-jquery-methods-you-should-be-using%2F&from=http%3A%2F%2Fwww.haojii.com%2F2011%2F04%2Fjquery-change-event-to-input-file-on-ie%2F">
                        <font size="-1" color="#667FFA" style="line-height: 1.65em; font-size: 12px !important;">你应该使用的20个有用的jQuery方法</font>
                    </a>
                </td>
            </tr>
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect?url=http%3A%2F%2Fwww.haojii.com%2F2010%2F01%2Fworking-with-events-part-3-more-event-delegation-with-jquery%2F&from=http%3A%2F%2Fwww.haojii.com%2F2011%2F04%2Fjquery-change-event-to-input-file-on-ie%2F">
                        <font size="-1" color="#667FFA" style="line-height: 1.65em; font-size: 12px !important;">Working with Events, Part 3: More Event Delegation with jQuery</font>
                    </a>
                </td>
            </tr>
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect?url=http%3A%2F%2Fwww.haojii.com%2F2010%2F05%2Fcool-demo-with-jquery-plugin-fancybox%2F&from=http%3A%2F%2Fwww.haojii.com%2F2011%2F04%2Fjquery-change-event-to-input-file-on-ie%2F">
                        <font size="-1" color="#667FFA" style="line-height: 1.65em; font-size: 12px !important;">Cool demo with jQuery plugin FancyBox</font>
                    </a>
                </td>
            </tr>
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect?url=http%3A%2F%2Fwww.haojii.com%2F2010%2F01%2Fjquery-1-4-released-the-15-new-features-you-must-know%2F&from=http%3A%2F%2Fwww.haojii.com%2F2011%2F04%2Fjquery-change-event-to-input-file-on-ie%2F">
                        <font size="-1" color="#667FFA" style="line-height: 1.65em; font-size: 12px !important;">jQuery1.4发布: 你必须知道的15个新特性</font>
                    </a>
                </td>
            </tr>
    
    <tr>
        <td  align="right">
            <a style="text-decoration: none !important;" href="http://www.wumii.com/widget/relatedItems" target="_blank" title="无觅相关文章插件">
                <font size="-1" color="#bbbbbb" style="display: block !important; font-family: arial !important; padding: 5px 0 !important; font-size: 12px !important; color: #bbb !important;">无觅</font>
            </a>
        </td>
    </tr>
</table>]]></content:encoded>
			<wfw:commentRss>http://www.haojii.com/2011/04/jquery-change-event-to-input-file-on-ie/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>使用jQuery UI sortable排序表格行的宽度问题</title>
		<link>http://www.haojii.com/2011/04/jquery-ui-sortable-problem-with-table-tr-row-width/</link>
		<comments>http://www.haojii.com/2011/04/jquery-ui-sortable-problem-with-table-tr-row-width/#comments</comments>
		<pubDate>Mon, 11 Apr 2011 14:57:32 +0000</pubDate>
		<dc:creator>Jacky</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[jquery-ui-sortable]]></category>
		<category><![CDATA[sortable]]></category>

		<guid isPermaLink="false">http://www.haojii.com/?p=532</guid>
		<description><![CDATA[遇到的问题是当我拖拽表格某一行排序的时候，这一行的宽度变得很小，下面是原图以及拖拽时候的难看效果 问题的根源是helper对象，这个拖拽的时候clone出来的对象丢失了样式属性，解决办法在stackoverflow找到 http://stackoverflow.com/questions/1307705/jquery-ui-sortable-with-table-and-tr-width 稍作优化之后的效果 (高亮显示拖拽的目标位置) 最近折腾了不少前端代码，比较耗费脑力，做个jQuery熟练工也没啥坏处。<table class="wumii-related-items" cellspacing="0" cellpadding="2" border="0" width="100%" style="clear: both;">
    
    <tr>
        <td ><b><font size="-1" color="#FF0000" style="display: block !important; padding: 20px 0 5px !important;">其他文章：</font></b></td>
    </tr>
    
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect?url=http%3A%2F%2Fwww.haojii.com%2F2010%2F04%2F20-helpful-jquery-methods-you-should-be-using%2F&from=http%3A%2F%2Fwww.haojii.com%2F2011%2F04%2Fjquery-ui-sortable-problem-with-table-tr-row-width%2F">
                        <font size="-1" color="#667FFA" style="line-height: 1.65em; font-size: 12px !important;">你应该使用的20个有用的jQuery方法</font>
                    </a>
                </td>
            </tr>
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect?url=http%3A%2F%2Fwww.haojii.com%2F2011%2F04%2Fjquery-change-event-to-input-file-on-ie%2F&from=http%3A%2F%2Fwww.haojii.com%2F2011%2F04%2Fjquery-ui-sortable-problem-with-table-tr-row-width%2F">
                        <font size="-1" color="#667FFA" style="line-height: 1.65em; font-size: 12px !important;">自定义input type=”file”的样式以及引出的相关技术问题</font>
                    </a>
                </td>
            </tr>
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect?url=http%3A%2F%2Fwww.haojii.com%2F2010%2F05%2Fcool-demo-with-jquery-plugin-fancybox%2F&from=http%3A%2F%2Fwww.haojii.com%2F2011%2F04%2Fjquery-ui-sortable-problem-with-table-tr-row-width%2F">
                        <font size="-1" color="#667FFA" style="line-height: 1.65em; font-size: 12px !important;">Cool demo with jQuery plugin FancyBox</font>
                    </a>
                </td>
            </tr>
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect?url=http%3A%2F%2Fwww.haojii.com%2F2010%2F06%2Fjquery-tips-pass-more-parameters-into-ajax-callback%2F&from=http%3A%2F%2Fwww.haojii.com%2F2011%2F04%2Fjquery-ui-sortable-problem-with-table-tr-row-width%2F">
                        <font size="-1" color="#667FFA" style="line-height: 1.65em; font-size: 12px !important;">jQuery Tips : 给AJAX回调函数传递额外参数</font>
                    </a>
                </td>
            </tr>
    
    <tr>
        <td  align="right">
            <a style="text-decoration: none !important;" href="http://www.wumii.com/widget/relatedItems" target="_blank" title="无觅相关文章插件">
                <font size="-1" color="#bbbbbb" style="display: block !important; font-family: arial !important; padding: 5px 0 !important; font-size: 12px !important; color: #bbb !important;">无觅</font>
            </a>
        </td>
    </tr>
</table>]]></description>
			<content:encoded><![CDATA[<p>遇到的问题是当我拖拽表格某一行排序的时候，这一行的宽度变得很小，下面是原图以及拖拽时候的难看效果</p>
<p><a rel="attachment wp-att-533" href="http://www.haojii.com/2011/04/jquery-ui-sortable-problem-with-table-tr-row-width/table_sort_normal/"><img class="aligncenter size-full wp-image-533" title="table_sort_normal" src="http://www.haojii.com/blog/wp-content/uploads/table_sort_normal.png" alt="" width="220" height="130" /></a><a rel="attachment wp-att-534" href="http://www.haojii.com/2011/04/jquery-ui-sortable-problem-with-table-tr-row-width/table_sort_drag/"></a></p>
<p><a rel="attachment wp-att-534" href="http://www.haojii.com/2011/04/jquery-ui-sortable-problem-with-table-tr-row-width/table_sort_drag/"><img class="aligncenter size-full wp-image-534" title="table_sort_drag" src="http://www.haojii.com/blog/wp-content/uploads/table_sort_drag.png" alt="" width="220" height="120" /></a></p>
<p>问题的根源是helper对象，这个拖拽的时候clone出来的对象丢失了样式属性，解决办法在stackoverflow找到 <a href="http://stackoverflow.com/questions/1307705/jquery-ui-sortable-with-table-and-tr-width">http://stackoverflow.com/questions/1307705/jquery-ui-sortable-with-table-and-tr-width</a></p>
<pre class="brush: jscript; title: ; notranslate">

var fixHelper = function(e, tr) {
 var $originals = tr.children();
 var $helper = tr.clone();
 $helper.children().each(function(index) {
 // Set helper cell sizes to match the original sizes
 $(this).width($originals.eq(index).width())
 });
 return $helper;
 };

$(&quot;table tbody&quot;).sortable({
 helper : fixHelper
 });
</pre>
<p>稍作优化之后的效果 (高亮显示拖拽的目标位置)</p>
<p><a rel="attachment wp-att-537" href="http://www.haojii.com/2011/04/jquery-ui-sortable-problem-with-table-tr-row-width/table_sort_drag_fixed/"><img class="aligncenter size-full wp-image-537" title="table_sort_drag_fixed" src="http://www.haojii.com/blog/wp-content/uploads/table_sort_drag_fixed.png" alt="" width="269" height="158" /></a></p>
<pre class="brush: jscript; title: ; notranslate">
//css
tr.ui-state-highlight td {
	background-color: yellow;
}
//javascript
$(&quot;table tbody&quot;).sortable({
placeholder : &quot;ui-state-highlight&quot;,
opacity: 0.6,
helper : fixHelper,
start : function(e, ui) {
 ui.placeholder.html(ui.helper.html());
},
change : function(event, ui) {
 $('tr.ui-state-highlight').html(ui.helper.html());
}
});
</pre>
<p>最近折腾了不少前端代码，比较耗费脑力，做个jQuery熟练工也没啥坏处。</p>
<table class="wumii-related-items" cellspacing="0" cellpadding="2" border="0" width="100%" style="clear: both;">
    
    <tr>
        <td ><b><font size="-1" color="#FF0000" style="display: block !important; padding: 20px 0 5px !important;">其他文章：</font></b></td>
    </tr>
    
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect?url=http%3A%2F%2Fwww.haojii.com%2F2010%2F04%2F20-helpful-jquery-methods-you-should-be-using%2F&from=http%3A%2F%2Fwww.haojii.com%2F2011%2F04%2Fjquery-ui-sortable-problem-with-table-tr-row-width%2F">
                        <font size="-1" color="#667FFA" style="line-height: 1.65em; font-size: 12px !important;">你应该使用的20个有用的jQuery方法</font>
                    </a>
                </td>
            </tr>
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect?url=http%3A%2F%2Fwww.haojii.com%2F2011%2F04%2Fjquery-change-event-to-input-file-on-ie%2F&from=http%3A%2F%2Fwww.haojii.com%2F2011%2F04%2Fjquery-ui-sortable-problem-with-table-tr-row-width%2F">
                        <font size="-1" color="#667FFA" style="line-height: 1.65em; font-size: 12px !important;">自定义input type=”file”的样式以及引出的相关技术问题</font>
                    </a>
                </td>
            </tr>
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect?url=http%3A%2F%2Fwww.haojii.com%2F2010%2F05%2Fcool-demo-with-jquery-plugin-fancybox%2F&from=http%3A%2F%2Fwww.haojii.com%2F2011%2F04%2Fjquery-ui-sortable-problem-with-table-tr-row-width%2F">
                        <font size="-1" color="#667FFA" style="line-height: 1.65em; font-size: 12px !important;">Cool demo with jQuery plugin FancyBox</font>
                    </a>
                </td>
            </tr>
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect?url=http%3A%2F%2Fwww.haojii.com%2F2010%2F06%2Fjquery-tips-pass-more-parameters-into-ajax-callback%2F&from=http%3A%2F%2Fwww.haojii.com%2F2011%2F04%2Fjquery-ui-sortable-problem-with-table-tr-row-width%2F">
                        <font size="-1" color="#667FFA" style="line-height: 1.65em; font-size: 12px !important;">jQuery Tips : 给AJAX回调函数传递额外参数</font>
                    </a>
                </td>
            </tr>
    
    <tr>
        <td  align="right">
            <a style="text-decoration: none !important;" href="http://www.wumii.com/widget/relatedItems" target="_blank" title="无觅相关文章插件">
                <font size="-1" color="#bbbbbb" style="display: block !important; font-family: arial !important; padding: 5px 0 !important; font-size: 12px !important; color: #bbb !important;">无觅</font>
            </a>
        </td>
    </tr>
</table>]]></content:encoded>
			<wfw:commentRss>http://www.haojii.com/2011/04/jquery-ui-sortable-problem-with-table-tr-row-width/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>jQuery Tips : 给AJAX回调函数传递额外参数</title>
		<link>http://www.haojii.com/2010/06/jquery-tips-pass-more-parameters-into-ajax-callback/</link>
		<comments>http://www.haojii.com/2010/06/jquery-tips-pass-more-parameters-into-ajax-callback/#comments</comments>
		<pubDate>Sat, 05 Jun 2010 09:15:07 +0000</pubDate>
		<dc:creator>Jacky</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[AJAX]]></category>
		<category><![CDATA[web开发]]></category>
		<category><![CDATA[高手必备]]></category>

		<guid isPermaLink="false">http://www.haojii.com/?p=325</guid>
		<description><![CDATA[讨论这个问题基于如下场景：点击页面上某个按钮之后，触发click事件，事件处理函数内部发送一个AJAX请求，AJAX回调函数更新页面的某一个部分 具体到这个例子，我们希望button1和button2点击之后，用AJAX的方式取example.html的内容，然后动态更新页面的id=callbackdemo3的div HTML如下：  第一种做法： 适用于最简单的情况，也是比较直观的做法，就是在ajax回调函数中，使用jQuery的id选择器$(“#callbackdemo3&#8243;)得到id为callbackdemo3的div后更新其HTML内容   第二种做法： 定义好一个接受额外参数的回调函数，然后在默认回调函数的内容调用这个预先定义好的回调函数  这样就能达到传递额外参数的目的了，较之第一种方法，此方法能比较方便的利用各个回调函数的上下文。   对于额外参数的重要性，不妨看一个稍微复杂一点点的HTML情况，我们希望更新button3下面的那个div的HTML，这个div没有id，那么如何做呢？  当然使用#callback_complexdemo&#62;div也是可以的，但是如果是更加复杂的HTML页面呢？如果没有id=callback_complexdemo呢？嵌套很深呢？ 这种情况下，我们就需要有效利用上下文参数这个特性了。 在click的事件处理函数load()中，我们可以方便的获得当前元素的位置var whereAmI = $(this); 这个whereAmI是个jQuery对象，然后在AJAX回调函数f3中，我们利用whereAmI即被点中的这个button想办法去获得想要的div 这一行代码新手有的人看不懂：$(&#8216;div&#8217;,$(whereAmI).closest(&#8216;div&#8217;)) 首先$closest_parent_div = $(whereAmI).closest(&#8216;div&#8217;)即查询获得whereAmI最近的父div对象 然后$(&#8216;div&#8217;,$closest_parent_div) 即在最近的父div对象这个上下文中，查找内部的div对象    希望通过这个小例子，能让大家学会如何给AJAX回调函数传递额外参数，以及实用且重要的上下文参数。<table class="wumii-related-items" cellspacing="0" cellpadding="2" border="0" width="100%" style="clear: both;">
    
    <tr>
        <td ><b><font size="-1" color="#FF0000" style="display: block !important; padding: 20px 0 5px !important;">其他文章：</font></b></td>
    </tr>
    
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect?url=http%3A%2F%2Fwww.haojii.com%2F2010%2F04%2F20-helpful-jquery-methods-you-should-be-using%2F&from=http%3A%2F%2Fwww.haojii.com%2F2010%2F06%2Fjquery-tips-pass-more-parameters-into-ajax-callback%2F">
                        <font size="-1" color="#667FFA" style="line-height: 1.65em; font-size: 12px !important;">你应该使用的20个有用的jQuery方法</font>
                    </a>
                </td>
            </tr>
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect?url=http%3A%2F%2Fwww.haojii.com%2F2010%2F01%2Fworking-with-events-part-3-more-event-delegation-with-jquery%2F&from=http%3A%2F%2Fwww.haojii.com%2F2010%2F06%2Fjquery-tips-pass-more-parameters-into-ajax-callback%2F">
                        <font size="-1" color="#667FFA" style="line-height: 1.65em; font-size: 12px !important;">Working with Events, Part 3: More Event Delegation with jQuery</font>
                    </a>
                </td>
            </tr>
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect?url=http%3A%2F%2Fwww.haojii.com%2F2010%2F05%2Fcool-demo-with-jquery-plugin-fancybox%2F&from=http%3A%2F%2Fwww.haojii.com%2F2010%2F06%2Fjquery-tips-pass-more-parameters-into-ajax-callback%2F">
                        <font size="-1" color="#667FFA" style="line-height: 1.65em; font-size: 12px !important;">Cool demo with jQuery plugin FancyBox</font>
                    </a>
                </td>
            </tr>
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect?url=http%3A%2F%2Fwww.haojii.com%2F2010%2F01%2Fjquery-1-4-released-the-15-new-features-you-must-know%2F&from=http%3A%2F%2Fwww.haojii.com%2F2010%2F06%2Fjquery-tips-pass-more-parameters-into-ajax-callback%2F">
                        <font size="-1" color="#667FFA" style="line-height: 1.65em; font-size: 12px !important;">jQuery1.4发布: 你必须知道的15个新特性</font>
                    </a>
                </td>
            </tr>
    
    <tr>
        <td  align="right">
            <a style="text-decoration: none !important;" href="http://www.wumii.com/widget/relatedItems" target="_blank" title="无觅相关文章插件">
                <font size="-1" color="#bbbbbb" style="display: block !important; font-family: arial !important; padding: 5px 0 !important; font-size: 12px !important; color: #bbb !important;">无觅</font>
            </a>
        </td>
    </tr>
</table>]]></description>
			<content:encoded><![CDATA[<p>讨论这个问题基于如下场景：点击页面上某个按钮之后，触发click事件，事件处理函数内部发送一个AJAX请求，AJAX回调函数更新页面的某一个部分</p>
<p>具体到这个例子，我们希望button1和button2点击之后，用AJAX的方式取example.html的内容，然后动态更新页面的id=callbackdemo3的div</p>
<p>HTML如下： </p>
<pre class="brush: xml; title: ; notranslate">
&lt;div id=&quot;callbackdemo1&quot;&gt;
	&lt;button id=&quot;button1&quot;&gt;ajax load1&lt;/button&gt;&lt;br/&gt;
&lt;/div&gt;
&lt;div id=&quot;callbackdemo2&quot;&gt;
	&lt;button id=&quot;button2&quot;&gt;ajax load2&lt;/button&gt;&lt;br/&gt;
&lt;/div&gt;

&lt;div id=&quot;callbackdemo3&quot; class=&quot;log&quot;&gt;&lt;/div&gt;

&lt;button onclick=&quot;$('.log').html('');&quot;&gt;clear&lt;/button&gt;
</pre>
<p><strong>第一种做法：</strong></p>
<p>适用于最<span style="color: #ff0000;">简单</span>的情况，也是比较<span style="color: #ff0000;">直观</span>的做法，就是在ajax回调函数中，使用jQuery的<span style="color: #ff0000;">id选择器</span>$(“#callbackdemo3&#8243;)得到id为callbackdemo3的div后更新其HTML内容</p>
<pre class="brush: jscript; title: ; notranslate">
$(&quot;#callbackdemo1&gt;#button1&quot;).click(
function load(){
	$.get(&quot;example.html&quot;,{ 'param[]': [&quot;var1&quot;, &quot;var2&quot;] },
		function f1(data, textStatus, XMLHttpRequest)
		{
			$(&quot;#callbackdemo3&quot;).html(data);
		}
		);
}
);
</pre>
<p><strong> </strong></p>
<p><strong>第二种做法：</strong></p>
<p>定义好一个接受额外参数的回调函数，然后在默认回调函数的内容调用这个预先定义好的回调函数</p>
<p> 这样就能达到传递额外参数的目的了，较之第一种方法，<span style="color: #ff0000;">此方法能比较方便的利用各个回调函数的上下文</span>。</p>
<pre class="brush: jscript; title: ; notranslate">
function callback_with_extraParam(data,param)
{
	param.html(data);
}
$(&quot;#callbackdemo2&gt;#button2&quot;).click(
function load(){
	var extraParam = $(&quot;#callbackdemo3&quot;)
	$.get(&quot;example.html&quot;,{ 'param[]': [&quot;var1&quot;, &quot;var2&quot;] },
		function f2(data)
		{
			callback_with_extraParam(data,extraParam);
		}
		);
}
);
</pre>
<p> </p>
<p>对于<span style="color: #ff0000;">额外参数的重要性</span>，不妨看一个稍微复杂一点点的HTML情况，我们希望更新button3下面的那个div的HTML，这个div没有id，那么如何做呢？ </p>
<pre class="brush: xml; title: ; notranslate">
&lt;div id=&quot;callback_complexdemo&quot;&gt;
  &lt;button id=&quot;button3&quot;&gt;ajax load3&lt;/button&gt;&lt;br/&gt;
  &lt;button onclick=&quot;$('div',$(this).closest('div')).html('');&quot;&gt;clear&lt;/button&gt;&lt;br/&gt;
  &lt;div&gt;&lt;/div&gt;
&lt;/div&gt;
</pre>
<p>当然使用#callback_complexdemo&gt;div也是可以的，但是如果是更加复杂的HTML页面呢？如果没有id=callback_complexdemo呢？嵌套很深呢？</p>
<p>这种情况下，我们就<span style="color: #ff0000;">需要有效利用上下文参数这个特性</span>了。</p>
<p>在click的事件处理函数<span style="color: #ff0000;">load()</span>中，我们可以方便的获得<span style="color: #ff0000;">当前元素</span>的位置var whereAmI = <span style="color: #ff0000;">$(this);<br />
</span>这个whereAmI是个jQuery对象，然后在AJAX回调函数f3中，我们利用whereAmI即被点中的这个button想办法去获得想要的div</p>
<p>这一行代码新手有的人看不懂：$(&#8216;div&#8217;,$(whereAmI).closest(&#8216;div&#8217;))</p>
<p>首先$closest_parent_div = $(whereAmI).closest(&#8216;div&#8217;)即查询获得whereAmI最近的父div对象</p>
<p>然后$(&#8216;div&#8217;,$closest_parent_div) 即在最近的父div对象这个上下文中，查找内部的div对象</p>
<pre class="brush: jscript; title: ; notranslate">
$(&quot;#callback_complexdemo&gt;#button3&quot;).click(
function load(){
	var whereAmI = $(this);
	$.get(&quot;example.html&quot;,{ 'param[]': [&quot;var1&quot;, &quot;var2&quot;] },
		function f3(data)
		{
			console.log(whereAmI);
			$('div',$(whereAmI).closest('div')).html(data);
		}
		);
}
);
</pre>
<p> </p>
<p> 希望通过这个小例子，能让大家学会如何给AJAX回调函数传递额外参数，以及实用且重要的上下文参数。</p>
]]></content:encoded>
			<wfw:commentRss>http://www.haojii.com/2010/06/jquery-tips-pass-more-parameters-into-ajax-callback/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Cool demo with jQuery plugin FancyBox</title>
		<link>http://www.haojii.com/2010/05/cool-demo-with-jquery-plugin-fancybox/</link>
		<comments>http://www.haojii.com/2010/05/cool-demo-with-jquery-plugin-fancybox/#comments</comments>
		<pubDate>Fri, 21 May 2010 07:40:25 +0000</pubDate>
		<dc:creator>Jacky</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[WebDev]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[web开发]]></category>

		<guid isPermaLink="false">http://www.haojii.com/?p=307</guid>
		<description><![CDATA[$(document).ready(function() { $("#login").fancybox({ 'padding' : 0, 'autoScale' : false, 'transitionIn' : 'none', 'transitionOut' : 'none' }); $("#flash").fancybox({ 'padding' : 0, 'autoScale' : false, 'transitionIn' : 'none', 'transitionOut' : 'none' }); }); 猛击我查看效果 A Flash Demo 代码如下：]]></description>
			<content:encoded><![CDATA[<p><script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script></p>
<p><script type="text/javascript" src="http://www.haojii.com/webdev/fancyboxdemo/fancybox/jquery.mousewheel-3.0.2.pack.js"></script></p>
<p><script type="text/javascript" src="http://www.haojii.com/webdev/fancyboxdemo/fancybox/jquery.fancybox-1.3.1.js"></script></p>
<link rel="stylesheet" type="text/css" href="http://www.haojii.com/webdev/fancyboxdemo/fancybox/jquery.fancybox-1.3.1.css" media="screen" />
<p><script type="text/javascript">
		$(document).ready(function() {
			$("#login").fancybox({
				'padding'			: 0,
				'autoScale'			: false,
				'transitionIn'		: 'none',
				'transitionOut'		: 'none'
			});
			$("#flash").fancybox({
				'padding'			: 0,
				'autoScale'			: false,
				'transitionIn'		: 'none',
				'transitionOut'		: 'none'
			});
		});
	</script></p>
<div>
<h1><a id="login" href="#register-form" title="This is the title for register form">猛击我查看效果</a></h1>
<div style="display:none">
<p><!-- Registration -->  </p>
<div id="register-form" style="width: 500px; height: 300px; margin:auto;">
<h1><a id="flash" href="http://www.adobe.com/jp/events/cs3_web_edition_tour/swfs/perform.swf">A Flash Demo</a></h1>
</p></div>
</p></div>
<p><!-- /Registration -->  </p>
</div>
<p>代码如下：</p>
<pre class="brush: xml; title: ; notranslate">
&lt;script type=&quot;text/javascript&quot; src=&quot;http://code.jquery.com/jquery-1.4.2.min.js&quot;&gt;&lt;/script&gt;

&lt;script type=&quot;text/javascript&quot; src=&quot;http://www.haojii.com/webdev/fancyboxdemo/fancybox/jquery.mousewheel-3.0.2.pack.js&quot;&gt;&lt;/script&gt;

&lt;script type=&quot;text/javascript&quot; src=&quot;http://www.haojii.com/webdev/fancyboxdemo/fancybox/jquery.fancybox-1.3.1.js&quot;&gt;&lt;/script&gt;

&lt;link rel=&quot;stylesheet&quot; type=&quot;text/css&quot; href=&quot;http://www.haojii.com/webdev/fancyboxdemo/fancybox/jquery.fancybox-1.3.1.css&quot; media=&quot;screen&quot; /&gt;

&lt;script type=&quot;text/javascript&quot;&gt;
		$(document).ready(function() {
			$(&quot;#login&quot;).fancybox({
				'padding'			: 0,
				'autoScale'			: false,
				'transitionIn'		: 'none',
				'transitionOut'		: 'none'
			});
			$(&quot;#flash&quot;).fancybox({
				'padding'			: 0,
				'autoScale'			: false,
				'transitionIn'		: 'none',
				'transitionOut'		: 'none'
			});
		});
	&lt;/script&gt;

&lt;div&gt;
&lt;h1&gt;&lt;a id=&quot;login&quot; href=&quot;#register-form&quot; title=&quot;This is the title for register form&quot;&gt;猛击我吧!&lt;/a&gt;&lt;/h1&gt;
    &lt;div style=&quot;display:none&quot;&gt; 

&lt;!-- Registration --&gt;
		&lt;div id=&quot;register-form&quot; style=&quot;width: 500px; height: 300px; margin:auto;&quot;&gt;
			&lt;h1&gt;&lt;a id=&quot;flash&quot; href=&quot;http://www.adobe.com/jp/events/cs3_web_edition_tour/swfs/perform.swf&quot;&gt;A Flash Demo&lt;/a&gt;&lt;/h1&gt;
		&lt;/div&gt;
   &lt;/div&gt;
&lt;!-- /Registration --&gt;  

&lt;/div&gt;
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.haojii.com/2010/05/cool-demo-with-jquery-plugin-fancybox/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>你应该使用的20个有用的jQuery方法</title>
		<link>http://www.haojii.com/2010/04/20-helpful-jquery-methods-you-should-be-using/</link>
		<comments>http://www.haojii.com/2010/04/20-helpful-jquery-methods-you-should-be-using/#comments</comments>
		<pubDate>Thu, 15 Apr 2010 09:06:33 +0000</pubDate>
		<dc:creator>Jacky</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[web开发]]></category>
		<category><![CDATA[翻译]]></category>

		<guid isPermaLink="false">http://www.haojii.com/?p=276</guid>
		<description><![CDATA[原文地址：20 Helpful jQuery Methods you Should be Using 原文作者：Andrew Burgess 这篇文章介绍了jQuery中有用的20个方法，1-20编号如下，本文没有对照原文逐句翻译，这个20个方法名称，我其实就是用下面第14个map()的方式取出来的，亮点如下，firebug真是个离不开的好工具。 说到工具，那就顺便再提一下一个简洁的jQuery代码调试工具：jQueryPad 支持代码高亮，不支持代码辅助，小问题是这个工具带的jQuery.js的版本旧了，需要自己更新一份到它的目录。 （当然，我还是最喜欢firebug，特别是网页复杂的时候） 1 after() / before() 这个无需多说了，上面的图就是个例子，就是在当前对象的前面或者后面插入内容，被插入的内容是当然对象的兄弟节点 2 change() 和click()或者hover()一样，它也是个事件处理器，这个change事件作用于 textarea, text input, select, 当目标元素的值改变的时候触发该事件。它不同于对象失去焦点时触发的事件foucusOut()和blur()。 change()事件对于客户端验证的任务最适合不过了，因为你不需要在输入字段值没有变化的时候重新验证字段。 3 Context 在jQuery中，使用选择器，其实默认作用于document这个上下文上 了解了这一点话，Context就简单了，它是一个属性兼参数 作为属性：每个jQuery对象，都有个context属性 作为参数：当使用jQuery选择器时，可以使用第二个参数context，细化了查询的范围 用Firebug试验一下就明白了！ 4 data() / removeData() 在元素上（确切的说应该是jQuery对象）上存储数据的一种办法 &#8230; <a href="http://www.haojii.com/2010/04/20-helpful-jquery-methods-you-should-be-using/">继续阅读 <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>原文地址：<a href="http://net.tutsplus.com/tutorials/javascript-ajax/20-helpful-jquery-methods-you-should-be-using/">20 Helpful jQuery Methods you Should be Using</a><br />
原文作者：<a title="Andrew Burgess" href="http://net.tutsplus.com/author/andrewburgess/">Andrew Burgess</a></p>
<p>这篇文章介绍了jQuery中有用的20个方法，1-20编号如下，本文没有对照原文逐句翻译，这个20个方法名称，我其实就是用下面第14个map()的方式取出来的，亮点如下，firebug真是个离不开的好工具。</p>
<p><a href="http://www.haojii.com/wp-content/uploads/20jQueryMethods.png"><img class="aligncenter size-full wp-image-277" title="20jQueryMethods" src="http://www.haojii.com/wp-content/uploads/20jQueryMethods.png" alt="" width="806" height="825" /></a></p>
<p>说到工具，那就顺便再提一下一个简洁的jQuery代码调试工具：<a href="http://www.paulstovell.com/jquerypad">jQueryPad</a></p>
<p>支持代码高亮，不支持代码辅助，小问题是这个工具带的jQuery.js的版本旧了，需要自己更新一份到它的目录。</p>
<p>（当然，我还是最喜欢firebug，特别是网页复杂的时候）</p>
<p><a href="http://www.haojii.com/wp-content/uploads/jQueryPad.png"><img class="aligncenter size-full wp-image-278" title="jQueryPad" src="http://www.haojii.com/wp-content/uploads/jQueryPad.png" alt="" width="834" height="595" /></a></p>
<h3>1 after() / before()</h3>
<p>这个无需多说了，上面的图就是个例子，就是在当前对象的前面或者后面插入内容，被插入的内容是当然对象的兄弟节点</p>
<h3>2 change()</h3>
<p>和click()或者hover()一样，它也是个事件处理器，这个change事件作用于 textarea, text input, select, 当目标元素的值改变的时候触发该事件。它不同于对象失去焦点时触发的事件foucusOut()和blur()。</p>
<p>change()事件对于客户端验证的任务最适合不过了，因为你不需要在输入字段值没有变化的时候重新验证字段。</p>
<pre class="brush: jscript; title: ; notranslate">
$(document).ready(
    function() {
$('input[type=text]').change(function () {
    switch (this.id) {
/* some validation code here */
case &quot;name&quot;:
alert(this.value+&quot;....&quot;);
break;
default:
alert(this.id);
break;
    }
});
    });

// HTML Form
Name: &lt;input id=&quot;name&quot; type=&quot;text&quot;/&gt;
</pre>
<h3>3 Context</h3>
<p>在jQuery中，使用选择器，其实默认作用于document这个上下文上</p>
<p>了解了这一点话，Context就简单了，它是一个属性兼参数</p>
<p>作为属性：每个jQuery对象，都有个context属性</p>
<p>作为参数：当使用jQuery选择器时，可以使用第二个参数context，细化了查询的范围</p>
<p>用Firebug试验一下就明白了！</p>
<h3>4 data() / removeData()</h3>
<p>在元素上（确切的说应该是jQuery对象）上存储数据的一种办法</p>
<h3>5 queue() / dequeue()</h3>
<p>用在jQuery动画效果上，可以方便的增加或者移除一个特效</p>
<h3>6 delay()</h3>
<p>暂停一段时间的动画效果</p>
<h3>7 bind(), unbind(),live(), and die()</h3>
<p>以前的文章说过了，不废话了</p>
<h3>8 eq()</h3>
<p>用数组下标的方式取得一组元素中的某一个</p>
<h3>9 get()</h3>
<p>取得jQuery元素对应的Dom对象格式</p>
<h3>10 grep()</h3>
<p>这个我挺喜欢，第二个参数是个用于过滤的回调函数，很容易懂的</p>
<pre class="brush: jscript; title: ; notranslate">
 var nums = '1,2,3,4,5,6,7,8,9,10'.split(',');

 nums = $.grep(nums, function(num, index) {
   // num = the current value for the item in the array
   // index = the index of the item in the array
   return num &gt; 5; // returns a boolean
 });

 console.log(nums) // 6,7,8,9,10
</pre>
<h3>11 Pseudo-Selectors</h3>
<pre class="brush: jscript; title: ; notranslate">
$(':animated'); // returns all elements currently animating
$(':contains(me)'); // returns all elements with the text 'me'
$(':empty'); // returns all elements with no child nodes or text
$(':parent'); // returns all elements with child nodes or text
$('li:even'); // returns all even-index elements (in this case, &lt;li&gt;s)
$('li:odd'); // can you guess?
$(':header'); // returns all h1 - h6s.
$('li:gt(4)'); // returns all elements with an (zero-based) index greater than the given number
$('li:lt(4)'); // returns all element with an index less than the given number
$(':only-child'); // returns all . . . well, it should be obvious
</pre>
<h3>12 isArray() / isEmptyObject() / isFunction() / isPlainObject()</h3>
<pre class="brush: jscript; title: ; notranslate">
 $.isArray([1, 2, 3]); // returns true
 $.isEmptyObject({}); // returns true
 $.isFunction(function () { /****/ }); // returns true

 function Person(name) {
     this.name = name
     return this;
 }
 $.isPlainObject({})); // returns true
 $.isPlainObject(new Object()); // returns true
 $.isPlainObject(new Person()); // returns false
</pre>
<h3>13 makeArray()</h3>
<p>使用jQuery选择器返回的都是jQuery对象，所以$.makeArray()变得挺实用的</p>
<pre class="brush: jscript; title: ; notranslate">
    var ps = $('p');
    $.isArray(ps); //returns false;
    ps = $.makeArray(ps);
    $.isArray(ps); // returns true;
</pre>
<h3>14 map()</h3>
<p>上面firebug的贴图中延伸过了，自己试试看吧</p>
<h3>15 parseJSON()</h3>
<p>把JSON格式的字符串结果解析成JSON对象</p>
<h3>16 proxy()</h3>
<p>$.proxy() 解决了函数调用的上下文问题</p>
<pre class="brush: jscript; title: ; notranslate">
 var person = {
   name : &quot;Andrew&quot;,
   meet : function () {
     alert('Hi! My name is ' + this.name);
   }
 };
 person.meet();   // 正常工作
 $('#test').click(person.meet); // 返回 Hi! My name is undefined 或者 Hi! My name is 空

$('#test').click($.proxy(person.meet, person));
// we could also do $.proxy(person, &quot;meet&quot;)
</pre>
<h3>17 replaceAll() / replaceWith()</h3>
<p>用来替换内容的，replaceWith更顺脑</p>
<pre class="brush: jscript; title: ; notranslate">
&lt;div class=&quot;error1&quot;&gt;error section 1&lt;/div&gt;
&lt;br/&gt;
&lt;div class=&quot;error2&quot;&gt;error section 2&lt;/div&gt;
&lt;br/&gt;
$('&lt;span class=fixed&gt;The error has been corrected&lt;/span&gt;').replaceAll('.error1');
&quot;$('.error2').replaceWith('&lt;span class=fixed&gt;The error has been corrected&lt;/span&gt;');
</pre>
<h3>18 serialize() / serializeArray()</h3>
<p>看例子吧，易懂</p>
<pre class="brush: xml; title: ; notranslate">
 &lt;form&gt;
     &lt;input type=&quot;text&quot; name=&quot;name&quot; value=&quot;John Doe&quot; /&gt;
     &lt;input type=&quot;text&quot; name=&quot;url&quot; value=&quot;http://www.example.com&quot; /&gt;
 &lt;/form&gt;
</pre>
<pre class="brush: jscript; title: ; notranslate">
console.log($('form').serialize());​​​ // logs : name=John+Doe&amp;url=http%3A%2F%2Fwww.example.com
console.log($('form').serializeArray());
// logs : [{ name : 'name', value : 'John Doe'} , { name : 'url', value : 'http://www.example.com' } ]
</pre>
<h3>19 siblings()</h3>
<p>返回所有兄弟节点</p>
<h3>20 wrap() / wrapAll() / wrapInner()</h3>
<p>在作用对象的外面，周围，或者里面，包一层东西</p>
<h3>Conclusion</h3>
<p>好好玩这些个方法吧！</p>
<p>&#8230;</p>
]]></content:encoded>
			<wfw:commentRss>http://www.haojii.com/2010/04/20-helpful-jquery-methods-you-should-be-using/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>jQuery1.4发布: 你必须知道的15个新特性</title>
		<link>http://www.haojii.com/2010/01/jquery-1-4-released-the-15-new-features-you-must-know/</link>
		<comments>http://www.haojii.com/2010/01/jquery-1-4-released-the-15-new-features-you-must-know/#comments</comments>
		<pubDate>Mon, 18 Jan 2010 13:44:28 +0000</pubDate>
		<dc:creator>Jacky</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[web开发]]></category>
		<category><![CDATA[翻译]]></category>

		<guid isPermaLink="false">http://www.haojii.com/?p=137</guid>
		<description><![CDATA[原文地址：jQuery 1.4 Released: The 15 New Features you Must Know 原文作者：James Padolsey 译文地址：jQuery1.4发布: 你必须知道的15个新特性 译文作者：Ji Hao 1. 传递属性给jQuery(&#8230;)构造器 早在1.4版本之前，jQuery就支持通过有用的”attr“方法为元素集合添加属性，参数可以传递属性的名-值对或者是一个指定了多个属性的对象。jQuery1.4则支持元素创建的时候传递一个属性对象作为jQuery构造器的第二个参数。 举例来说，如果你要用jQuery1.4创建一个有多个属性的超链接对象，用如下简单的代码即可实现： 你可能已经注意到了”text”属性——可能你正怀疑它在这里出现是干啥的，毕竟超链接这玩意没有”text”属性！好吧，jQuery1.4其实统一了它自身的一些方法接受某些属性的行为。上面指定的”text”属性将会引起jQuery调用”.text()”方法，传递”Go to Google!”作为它的参数。 一个现实中更好点的例子： “id”被作为一个普通的属性添加，而”css”和”click”属性则触发了相应方法的调用。上面的代码在1.4之前需要链式的这样写出来： 更多关于构造器方法请参考文档： jQuery(…) 2. 所有的”until”方法! 在1.4中DOM遍历兵工厂里加入了3个新的方法， ”nextUntil“, “prevUntil“和 “parentsUntil“。这3个方法都是朝着某个方向遍历DOM直到指定的选择器条件满足。假定你有如下的水果列表： 如果你要选择”Apple”后面的直到”Strawberry”为止的所有列表元素，可以用如下简单的代码即可实现： 更多请参考文档：prevUntil, nextUntil, parentsUntil 3. 绑定多个事件处理器 除了将多个事件绑定代码链式的写在一起之外，你还可以在一个bind方法里写多个事件绑定代码如下： 这种写法对于.one()方法同样有效 更多请参考文档：.bind(…) &#8230; <a href="http://www.haojii.com/2010/01/jquery-1-4-released-the-15-new-features-you-must-know/">继续阅读 <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>原文地址：<a href="http://net.tutsplus.com/tutorials/javascript-ajax/jquery-1-4-released-the-15-new-features-you-must-know/">jQuery 1.4 Released: The 15 New Features you Must Know</a><br />
原文作者：<a title="Visit James Padolsey’s website" rel="external" href="http://james.padolsey.com/">James Padolsey</a></p>
<p>译文地址：<a href="http://www.haojii.com/2010/01/jquery-1-4-released-the-15-new-features-you-must-know/">jQuery1.4发布: 你必须知道的15个新特性<br />
</a>译文作者：<a href="http://www.haojii.com" target="_blank">Ji Hao</a></p>
<h3>1. 传递属性给jQuery(&#8230;)构造器</h3>
<p>早在1.4版本之前，jQuery就支持通过有用的”<a href="http://api.jquery.com/attr/" target="_blank">attr</a>“方法为元素集合添加属性，参数可以传递属性的名-值对或者是一个指定了多个属性的对象。jQuery1.4则支持元素创建的时候传递一个属性对象作为jQuery构造器的第二个参数。</p>
<p>举例来说，如果你要用jQuery1.4创建一个有多个属性的超链接对象，用如下简单的代码即可实现：</p>
<pre class="brush: jscript; title: ; notranslate">
jQuery('&lt;a/&gt;', {
    id: 'foo',
    href: 'http://google.com',
    title: 'Become a Googler',
    rel: 'external',
    text: 'Go to Google!'
});
</pre>
<p>你可能已经注意到了”text”属性——可能你正怀疑它在这里出现是干啥的，毕竟超链接这玩意没有”text”属性！好吧，jQuery1.4其实统一了它自身的一些方法接受某些属性的行为。上面指定的”text”属性将会引起jQuery调用”.text()”方法，传递”Go to Google!”作为它的参数。</p>
<p>一个现实中更好点的例子：</p>
<pre class="brush: jscript; title: ; notranslate">
jQuery('&lt;div/&gt;', {
    id: 'foo',
    css: {
        fontWeight: 700,
        color: 'green'
    },
    click: function(){
        alert('Foo has been clicked!');
    }
});
</pre>
<p>“id”被作为一个普通的属性添加，而”css”和”click”属性则触发了相应方法的调用。上面的代码在1.4之前需要链式的这样写出来：</p>
<pre class="brush: jscript; title: ; notranslate">
jQuery('&lt;div/&gt;')
    .attr('id', 'foo')
    .css({
        fontWeight: 700,
        color: 'green'
    })
    .click(function(){
        alert('Foo has been clicked!');
    });
</pre>
<p><a href="http://api.jquery.com/jQuery/">更多关于构造器方法请参考文档： jQuery(…)</a></p>
<h3>2. 所有的”until”方法!</h3>
<p>在1.4中DOM遍历兵工厂里加入了3个新的方法， ”<code>nextUntil</code>“, “<code>prevUntil</code>“和 “<code>parentsUntil</code>“。这3个方法都是朝着某个方向遍历DOM直到指定的选择器条件满足。假定你有如下的水果列表：</p>
<pre class="brush: xml; title: ; notranslate">
&lt;ul&gt;
    &lt;li&gt;Apple&lt;/li&gt;
    &lt;li&gt;Banana&lt;/li&gt;
    &lt;li&gt;Grape&lt;/li&gt;

    &lt;li&gt;Strawberry&lt;/li&gt;
    &lt;li&gt;Pear&lt;/li&gt;
    &lt;li&gt;Peach&lt;/li&gt;
&lt;/ul&gt;
</pre>
<p>如果你要选择”Apple”后面的直到”Strawberry”为止的所有列表元素，可以用如下简单的代码即可实现：</p>
<pre class="brush: jscript; title: ; notranslate">
jQuery('ul li:contains(Apple)').nextUntil(':contains(Pear)');
// Selects Banana, Grape, Strawberry
</pre>
<p>更多请参考文档：<a href="http://api.jquery.com/prevUntil/">prevUntil</a>, <a href="http://api.jquery.com/nextUntil/">nextUntil</a>, <a href="http://api.jquery.com/parentsUntil/">parentsUntil</a></p>
<h3>3. 绑定多个事件处理器</h3>
<p>除了将多个事件绑定代码链式的写在一起之外，你还可以在一个bind方法里写多个事件绑定代码如下：</p>
<pre class="brush: jscript; title: ; notranslate">jQuery('#foo).bind({
    click: function() {
        // do something
    },
    mouseover: function() {
        // do something
    },
    mouseout: function() {
        // do something
    }
})
</pre>
<p>这种写法对于.one()方法同样有效</p>
<p>更多请参考文档：<a href="http://api.jquery.com/bind/">.bind(…)</a></p>
<h3>4. 按照每个属性的擦除（Easing）效果</h3>
<p>以前你只能为单个动画指定其擦除效果，现在你能为当前定义动画效果的每个属性来指定擦除效果。jQuery包含了两个擦除效果”linear” 和”swing”（默认）.其他的效果你需要<a href="http://gsgd.co.uk/sandbox/jquery/easing/jquery.easing.1.3.js" target="_blank">单独下载</a>。</p>
<p>要为每个属性指定擦除效果，只要把目标属性定义为数组即可，数组的第一个值是你要的动画效果设置的属性值，第二个值是擦除效果函数使用的值：</p>
<pre class="brush: jscript; title: ; notranslate">jQuery('#foo').animate({
    left: 500,
    top: [500, 'easeOutBounce']
}, 2000);
</pre>
<p> </p>
<p><a href="http://james.padolsey.com/demos/jquery/easing/easing-jq14.html">看看这段代码的实际运行效果!</a></p>
<p>你还可以在可选参数options对象属性”specialEasing”里按照名-值对的形式定义每个属性的擦除效果：</p>
<pre class="brush: jscript; title: ; notranslate">jQuery('#foo').animate({
    left: 500,
    top: 500
}, {
    duration: 2000,
    specialEasing: {
        top: 'easeOutBounce'
    }
});
</pre>
<p><strong>原文编辑注：本文的作者James Padolsey谦虚了，这个新特性其实是他的主意。</strong></p>
<p><a href="http://api.jquery.com/animate/#per-property-easing">更多请参考文档： per-property easing</a></p>
<h3>5. 全新的Live事件代理！</h3>
<p>jQuery1.4增加了对”<strong>submit</strong>“, “<strong>change</strong>“, “<strong>focus</strong>” 和”<strong>blur</strong>“事件的代理支持。在jQuery中我们使用”.live()”方法来代理事件。当你需要对很多元素进行事件处理器注册的时候很有用，或者是当新的元素在将来被加入到DOM文档中我们却需要对其进行事件处理器绑定的情况下（使用”.live()”方法比进行重新绑定更高效）（译者注：更多关于jQuery事件代理请参考：<a title="永久链接: Working with Events, Part 3: More Event Delegation with jQuery" rel="bookmark" href="http://www.haojii.com/2010/01/working-with-events-part-3-more-event-delegation-with-jquery/">Working with Events, Part 3: More Event Delegation with jQuery</a>）</p>
<p>但是，要小心哪！你必须使用事件的名称，如果你要代理”focus”和”blur”，则必须用”<strong>focusin</strong>“和”<strong>focusout</strong>”</p>
<pre class="brush: jscript; title: ; notranslate">jQuery('input').live('focusin', function(){
    // do something with this
});
</pre>
<h3>6. 控制函数的上下文</h3>
<p>jQuery1.4在其命名空间下提供了一个新的”proxy”函数。这个函数接受两个参数，一个”scope”加一个方法名，或者是一个函数加目标作用域。JavaScript的”this”关键字是非常难掌握的。有时候你希望它是你之前创建出来的对象而不是一个元素。</p>
<p>举个例子：我们有如下的一个”app”对象，它有两个属性，一个”clickHandler”方法和一个config对象：</p>
<pre class="brush: jscript; title: ; notranslate">var app = {
    config: {
        clickMessage: 'Hi!'
    },
    clickHandler: function() {
        alert(this.config.clickMessage);
    }
};
</pre>
<p>“clickHanlder”方法在被这样调用时”app.clickHandler()”将有”app”对象作为其上下文，也就是说”this”关键字访问的就是”app”。如果我们只是做这样的简单调用，这个工作起来完全没有问题：</p>
<pre class="brush: jscript; title: ; notranslate">
app.clickHandler(); // &quot;Hi!&quot; is alerted
</pre>
<p>让我们来试试将其作为事件处理器来绑定到某个事件上:</p>
<pre class="brush: jscript; title: ; notranslate">
jQuery('a').bind('click', app.clickHandler);
</pre>
<p>当我们点击超链接的时候，它看上去并没有工作（因为没有警告消息弹出来）。这是因为jQuery（以及大多数健全的事件模型）都默认的将事件处理器的上下文设置成了事件目标元素——即：使用”this”访问的其实是被点击的元素。但是我们并不想要这样的结果，我们希望”this”能够访问”app”对象。在jQuery1.4中实现这个再容易不过了:</p>
<pre class="brush: jscript; title: ; notranslate">jQuery('a').bind(
    'click',
    jQuery.proxy(app, 'clickHandler')
);</pre>
<p>现在不管什么时候点击超链接，总是会有”Hi!”这个警告消息。</p>
<p>这个proxy函数返回你的函数的一个包装过的版本，”this”被设置成你指定的值。proxy函数在其他上下文也是有用的，例如传递一个回调函数给其他的jQuery方法或者传递给插件。</p>
<p>更多请参考文档：<a href="http://api.jquery.com/jQuery.proxy"><code>jQuery.proxy</code></a></p>
<h3>7. 延迟一个动画队列</h3>
<p>你现在可以为你的动画队列设置一个延迟。事实上任何队列都能设置延迟，但是最通用的场景应该是”fx”队列。它允许你在动画之间暂停，而不用再使用回调函数和”setTimeout”写的乱七八糟的。”.delay()”的第一个参数是你要延迟的毫秒数。</p>
<pre class="brush: jscript; title: ; notranslate">jQuery('#foo')
    .slideDown() // Slide down
    .delay(200) // Do nothing for 200 ms
    .fadeIn(); // Fade in
</pre>
<p>如果你要延迟默认的”fx”队列之外的队列，则需要传递队列的名称作为第二个参数。</p>
<p>更多请参考文档：<a href="http://api.jquery.com/delay"><code>.delay(…)</code></a></p>
<h3>8. 检查是否一个元素包含某些元素</h3>
<p>jQuery1.4是的检查一个元素或者一个集合是否”.has()”某些元素更加容易。程序上等同于jQuery选择过滤器”:has()”。这个方法将选择当前集合内的符合参数（选择器）的所有元素。</p>
<pre class="brush: jscript; title: ; notranslate">jQuery('div').has('ul');</pre>
<p>上面的这行代码将选择所有包含UL元素的所有DIV元素。这个情况下你用选择过滤器 (“:has()”)也够用了，但是这个方法在你需要用编程的方式过滤一个集合的时候是很有用的。</p>
<p>jQuery1.4 在jQuery名称空间下还提供了一个 “contains”函数。这是一个底层的函数，接受两个DOM节点作为参数，返回boolean值以指示第二个元素是否在第一个元素内。看下面的例子:</p>
<pre class="brush: jscript; title: ; notranslate">jQuery.contains(document.documentElement, document.body);
// Returns true - &lt;body&gt; is within &lt;html&gt;</pre>
<p>更多请参考文档：<a href="http://api.jquery.com/has/"><code>.has(…)</code></a>, <a href="http://api.jquery.com/jQuery.contains/"><code>jQuery.contains(…)</code></a></p>
<h3>9.  解除元素的包装</h3>
<p>有”.wrap()”方法已经一段时间了，jQuery1.4新增了”.unwrap()”方法做的是和”wrap()”完全相反的事情。假定有如下的DOM结构:</p>
<pre class="brush: xml; title: ; notranslate">&lt;div&gt;
    &lt;p&gt;Foo&lt;/p&gt;
&lt;/div&gt;
</pre>
<p>我们可以解除段落元素的包装：</p>
<pre class="brush: jscript; title: ; notranslate">jQuery('p').unwrap();</pre>
<p>结果DOM结构如下:</p>
<pre class="brush: xml; title: ; notranslate">
    &lt;p&gt;Foo&lt;/p&gt;
</pre>
<p>本质上，这个方法简单的去除了任何元素的父元素</p>
<p>更多请参考文档：<a href="http://api.jquery.com/unwrap/"><code>.unwrap(…)</code></a></p>
<h3>10. 删除元素而不删除其数据</h3>
<p>新的 ”<code><strong>.detach()</strong></code>“方法允许你从DOM文档中删除元素，和”.remove()”方法很像。关键的区别在于这个方法不会删除jQuery保存在这个元素上的数据。这些数据也包含使用”.data()”加上去的数据，也包含使用jQuery事件机制加上去的事件处理器。</p>
<p>这个适用于需要从DOM删除元素然后还要再加入DOM中的情况。被.detach的元素的事件监听器以及其他数据都会被保留。</p>
<pre class="brush: jscript; title: ; notranslate">

var foo = jQuery('#foo');

// Bind an important event handler
foo.click(function(){
    alert('Foo!');
});

foo.detach(); // Remove it from the DOM

// … do stuff

foo.appendTo('body'); // Add it back to the DOM

foo.click(); // alerts &quot;Foo!&quot;
</pre>
<p>更多请参考文档：<a href="http://api.jquery.com/detach"><code>.detach(…)</code></a></p>
<h3>11. index(…)的增强</h3>
<p>jQuery1.4提供了两种新的方法使用”.index()”方法。之前，你只能传递一个元素作为它的参数，改方法返回一个数字只是当前集合中目标元素的位置。</p>
<p>如果不传参数，则返回当前元素在同辈元素中的位置。假定我们有下面的DOM结构：</p>
<pre class="brush: xml; title: ; notranslate">
&lt;ul&gt;
    &lt;li&gt;Apple&lt;/li&gt;
    &lt;li&gt;Banana&lt;/li&gt;
    &lt;li&gt;Grape&lt;/li&gt;

    &lt;li&gt;Strawberry&lt;/li&gt;
    &lt;li&gt;Pear&lt;/li&gt;
    &lt;li&gt;Peach&lt;/li&gt;
&lt;/ul&gt;
</pre>
<p>当一个列表选项被点击的时候你想要知道他在其他列表选项中的位置：</p>
<pre class="brush: jscript; title: ; notranslate">
jQuery('li').click(function(){
    alert( jQuery(this).index() );
});
</pre>
<p>jQuery1.4还允许你指定一个选择器作为”.index()”方法的第一个参数，这么做将返回当前元素在选择器工作产生的结果集里的位置。</p>
<p>要注意的是这个方法返回整数值，如果选择器没有匹配的结果则返回-1</p>
<p>更多请参考文档：<a href="http://api.jquery.com/index"><code>.index(…)</code></a></p>
<h3>12. DOM操作方法接受回调函数作为参数</h3>
<p>现在大多数的DOM操作方法都支持接受一个函数作为单个参数（或者第二个参数，如果是”.css()”和”.attr()”方法的话）。这个传递的函数将会为每个集合中的元素都运行一遍，函数的返回结果将作为DOM操作方法的值。</p>
<p>下面的方法都有接受回调函数作为参数的能力：</p>
<ul>
<li><a href="http://api.jquery.com/after">after</a></li>
<li><a href="http://api.jquery.com/before">before</a></li>
<li><a href="http://api.jquery.com/append">append</a></li>
<li><a href="http://api.jquery.com/prepend">prepend</a></li>
<li><a href="http://api.jquery.com/addClass">addClass</a></li>
<li><a href="http://api.jquery.com/toggleClass">toggleClass</a></li>
<li><a href="http://api.jquery.com/removeClass">removeClass</a></li>
<li><a href="http://api.jquery.com/wrap">wrap</a></li>
<li><a href="http://api.jquery.com/wrapAll">wrapAll</a></li>
<li><a href="http://api.jquery.com/wrapInner">wrapInner</a></li>
<li><a href="http://api.jquery.com/val">val</a></li>
<li><a href="http://api.jquery.com/text">text</a></li>
<li><a href="http://api.jquery.com/replaceWith">replaceWith</a></li>
<li><a href="http://api.jquery.com/css">css</a></li>
<li><a href="http://api.jquery.com/attr">attr</a></li>
<li><a href="http://api.jquery.com/html">html</a></li>
</ul>
<p>在这个回调函数里，你可以通过”this”访问当前正在遍历的元素，回调函数的第一个参数的值是当然遍历元素的位置。</p>
<pre class="brush: jscript; title: ; notranslate">
jQuery('li').html(function(i){
    return 'Index of this list item: ' + i;
});
</pre>
<p>还有，上面某些方法，在回调函数中还可以接收第二个参数。如果你正在调用一个设值方法(如”.html()”或者”.attr(&#8216;href&#8217;)”)你可以访问当前要设置成的值，例如:</p>
<pre class="brush: jscript; title: ; notranslate">
jQuery('a').attr('href', function(i, currentHref){
    return currentHref + '?foo=bar';
}); </pre>
<p>正如你所看到的使用”.css()”和”.attr()”方法的时候，你可以传递函数作为第二个参数，因为第一个参数是你想要改变的属性的名称。</p>
<pre class="brush: jscript; title: ; notranslate">
jQuery('li').css('color', function(i, currentCssColor){
    return i % 2 ? 'red' : 'blue';
});
</pre>
<h3>13. 判断对象的类型</h3>
<p>jQuery1.4增加了两个副主函数（在jQuery名称空间下）帮助你检测正在处理的对象类型。</p>
<p>首先，有个”isEmptyObject”，这个函数返回boolean值，指示传递的对象是否为空（没有属性-直接或者间接的）。其次，有个”isPlainObject”，这个函数返回boolean值，指示传递的对象是否是一个纯的JavaScript对象，即使用”{}”或者”new Object()”创建出来的对象。</p>
<pre class="brush: jscript; title: ; notranslate">
jQuery.isEmptyObject({}); // true
jQuery.isEmptyObject({foo:1}); // false

jQuery.isPlainObject({}); // true
jQuery.isPlainObject(window); // false
jQuery.isPlainObject(jQuery()); // false
</pre>
<p>更多请参考文档： <a href="http://api.jquery.com/jQuery.isPlainObject"><code>isPlainObject(…)</code></a>, <a href="http://api.jquery.com/jQuery.isEmptyObject"><code>isEmptyObject(…)</code></a></p>
<h3>14. closest()的增强</h3>
<p>jQuery的”.closest()”方法现在能接受一组选择器作为参数。这个特性使得你在遍历一个元素祖先节点的时候，或者查找（多个）含有某些特定字符的最近元素的时候更有用。</p>
<p>除此之外，本方法还接受一个context作为其第二个参数，意思是你能控制遍历的深度。这两项增加适用的场景不是很多，但是jQuery内部使用这个方法来获得更好的性能。</p>
<p>更多请参考文档：<a href="http://api.jquery.com/closest"><code>.closest(…)</code></a></p>
<h3>15. 新事件！focusIn 和 focusOut</h3>
<p>其实上文已经提到，要代理”focus”和”blur”事件，你必须使用新的事件名称”focusin”和”focusout”。这些事件允许你在元素或者某元素的子元素获得焦点的时候干一些事情。</p>
<pre class="brush: jscript; title: ; notranslate">
jQuery('form')
    .focusin(function(){
        jQuery(this).addClass('focused');
    });
    .focusout(function(){
        jQuery(this).removeClass('focused');
    });
</pre>
<p>你还应该注意到的一点是，这些事件是不传播的(冒泡),他们是捕获型事件。意思就是，最外层的元素首先触发该事件，然后才是”目标”元素。</p>
<p>更多请参考文档：<a href="http://api.jquery.com/focusin"><code>focusIn</code></a> 和 <a href="http://api.jquery.com/focusout"><code>focusOut</code></a> 事件</p>
<h3>享受最受期望的，最具特色的，到目前为止性能最好的jQuery1.4吧！</h3>
<p>好吧，差不多了。我已经把自己认为对你们有影响的新特性涵盖到了。</p>
<p>如果你还没有准备好，应该看看”<strong><a href="http://jquery14.com/">14 days of jQuery</a></strong>“，一个很酷的为jQuery1.4发布以及jQuery4岁生日准备的在线活动。</p>
<p>还有不要忘记看看新的<a href="http://api.jquery.com/"><strong>API 文档</strong></a>!</p>
<p>&#8211;</p>
]]></content:encoded>
			<wfw:commentRss>http://www.haojii.com/2010/01/jquery-1-4-released-the-15-new-features-you-must-know/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Working with Events, Part 3: More Event Delegation with jQuery</title>
		<link>http://www.haojii.com/2010/01/working-with-events-part-3-more-event-delegation-with-jquery/</link>
		<comments>http://www.haojii.com/2010/01/working-with-events-part-3-more-event-delegation-with-jquery/#comments</comments>
		<pubDate>Sun, 17 Jan 2010 03:18:00 +0000</pubDate>
		<dc:creator>Jacky</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[web开发]]></category>
		<category><![CDATA[翻译]]></category>

		<guid isPermaLink="false">http://www.haojii.com/?p=129</guid>
		<description><![CDATA[// 原文地址：http://www.learningjquery.com/2009/09/working-with-events-part-3-more-event-delegation-with-jquery 原文作者:  Louis-Rémi Babé 正如本系列的第一篇文章中描述的那样，事件代理是利用事件冒泡机制来避免多次绑定事件监听器的一种办法。jQuery1.3和即将到来的jQuery1.4有很多新的特性可以使你的网页中使用事件代理更容易。这篇指南的目标就是帮助你理解这些新特性是如何工作的。 从传统的事件监听到事件代理 既然一个DOM元素上发生的事件会被传递到它所有的祖先元素（或者说是DOM节点）上，那么一个事件监听器就能被绑定在众多DOM元素的单一的那个祖先节点上，而不用为所有的DOM元素每个都单独绑定事件监听器。 看下面的列表先，再考虑下面的问题： 如果我们想知道被点击的列表元素的class,使用传统事件监听器的jQuery代码应该是这样写的： 传递给事件处理器的参数event对象有一个target属性，对应于被点击的元素。 使用事件代理的等价的代码是这样写的： 试试看实际效果: The first item. The second item. The third item. The fourth item. Class of the last clicked item:? 事件代理有两个主要的优势： 1. 使用一个事件监听器代替多个事件监听器明显更快 2. 任何页面加载完成之后动态新插入的元素也将会拥有相同的行为(在Working with Events, Part 1中已经演示过了) &#8230; <a href="http://www.haojii.com/2010/01/working-with-events-part-3-more-event-delegation-with-jquery/">继续阅读 <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p><script src="http://www.google.com/jsapi"></script><script type="text/javascript">// <![CDATA[
    google.load("jquery", "1.3.2");
// ]]&gt;</script></p>
<p><script src="http://www.haojii.com/webdev/working-with-events/events3.js" type="text/javascript"></script><br />
<script src="http://www.haojii.com/webdev/working-with-events/loadcss3.js" type="text/javascript"></script></p>
<p>原文地址：<a href="http://www.learningjquery.com/2009/09/working-with-events-part-3-more-event-delegation-with-jquery">http://www.learningjquery.com/2009/09/working-with-events-part-3-more-event-delegation-with-jquery</a><br />
原文作者:  <a href="http://www.lrbabe.com/">Louis-Rémi Babé</a></p>
<p>正如<a href="http://www.haojii.com/2010/01/working-with-events-part-1/">本系列的第一篇文章</a>中描述的那样，事件代理是利用事件冒泡机制来避免多次绑定事件监听器的一种办法。jQuery1.3和即将到来的jQuery1.4有很多新的特性可以使你的网页中使用事件代理更容易。这篇指南的目标就是帮助你理解这些新特性是如何工作的。</p>
<h4>从传统的事件监听到事件代理</h4>
<p>既然一个DOM元素上发生的事件会被传递到它所有的祖先元素（或者说是DOM节点）上，那么一个事件监听器就能被绑定在众多DOM元素的单一的那个祖先节点上，而不用为所有的DOM元素每个都单独绑定事件监听器。</p>
<p>看下面的列表先，再考虑下面的问题：</p>
<pre class="brush: xml; title: ; notranslate">
&lt;ul class=&quot;myList&quot;&gt;
  &lt;li class=&quot;red&quot;&gt;The first item.&lt;/li&gt;
  &lt;li class=&quot;green&quot;&gt;The second item.&lt;/li&gt;
  &lt;li class=&quot;yellow&quot;&gt;The third item.&lt;/li&gt;
  &lt;li class=&quot;blue&quot;&gt;The fourth item.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Class of the last clicked item: &lt;span id=&quot;display&quot;&gt; &lt;/span&gt;
&lt;/p&gt;
</pre>
<p>如果我们想知道被点击的列表元素的class,使用传统事件监听器的jQuery代码应该是这样写的：</p>
<pre class="brush: jscript; title: ; notranslate">
$(&quot;li&quot;).click( function( event ) {
  $(&quot;#display&quot;).text(event.target.className);
});
</pre>
<p>传递给事件处理器的参数event对象有一个<strong>target</strong>属性，对应于被点击的元素。</p>
<p>使用事件代理的等价的代码是这样写的：</p>
<pre class="brush: jscript; title: ; notranslate">
$(&quot;ul&quot;).click( function( event ) {
  $(&quot;#display&quot;).text(event.target.className);
});
</pre>
<p>试试看实际效果:</p>
<div id="test1" class="events-test">
<ul class="myList">
<li class="red">The first item.</li>
<li class="green">The second item.</li>
<li class="yellow">The third item.</li>
<li class="blue">The fourth item.</li>
</ul>
<p>Class of the last clicked item:<span class="display">?</span></p>
</div>
<p>事件代理有两个主要的优势：<br />
1. 使用一个事件监听器代替多个事件监听器明显更快<br />
2. 任何页面加载完成之后动态新插入的元素也将会拥有相同的行为(在<a href="http://www.haojii.com/2010/01/working-with-events-part-1/">Working with Events, Part 1</a>中已经演示过了)</p>
<p>这个转换成事件代理太简单了，因为我们原来的目标只是显示列表元素的class。使用前面的这个代码片断，无序列表本身的class(myList,点列表那个黑点的左边就能看出效果)也会被显示出来。因此，我们还应该判断一下点击的目标是个<strong>&lt;li&gt;</strong>元素。</p>
<pre class="brush: jscript; title: ; notranslate">
$(&quot;ul&quot;).click( function( event ) {
  if(event.target.nodeName == &quot;LI&quot;) {
 $(&quot;#display&quot;).text(event.target.className);
  }
});
</pre>
<p>试试看现在的效果:</p>
<div id="test2" class="events-test">
<ul class="myList">
<li class="red">The first item.</li>
<li class="green">The second item.</li>
<li class="yellow">The third item.</li>
<li class="blue">The fourth item.</li>
</ul>
<p>Class of the last clicked item: <span class="display">?</span></p>
</div>
<h4>扫描event.target的祖先节点: .closest() 方法</h4>
<p>操作像上面的例子一样如此简单的DOM文档，使用事件代理非常容易搞定。但是如果列表项里还包含子元素的话事情就会变得复杂许多，如下面这个列表元素：</p>
<pre class="brush: xml; title: ; notranslate">
&lt;ul class=&quot;myList&quot;&gt;
  &lt;li class=&quot;red&quot;&gt;&lt;b&gt;The &lt;i&gt;first &lt;u&gt;item&lt;/u&gt;&lt;/i&gt;&lt;/b&gt;.&lt;/li&gt;
  &lt;li class=&quot;green&quot;&gt;&lt;b&gt;The &lt;i&gt;second &lt;u&gt;item&lt;/u&gt;&lt;/i&gt;&lt;/b&gt;.&lt;/li&gt;
  &lt;li class=&quot;yellow&quot;&gt;&lt;b&gt;The &lt;i&gt;third &lt;u&gt;item&lt;/u&gt;&lt;/i&gt;&lt;/b&gt;.&lt;/li&gt;
  &lt;li class=&quot;blue&quot;&gt;&lt;b&gt;The &lt;i&gt;fourth &lt;u&gt;item&lt;/u&gt;&lt;/i&gt;&lt;/b&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Class of the last clicked item: &lt;span id=&quot;display&quot;&gt; &lt;/span&gt;
&lt;/p&gt;
</pre>
<p>这种情况下，如果用户点击了 item 这个单词，<strong>event.target</strong>就会使<strong>&lt;u&gt;</strong>.这样的话就必须遍历当前目标元素的所有的祖先节点，来找到我们关心的元素：即<strong>&lt;li&gt;</strong>.</p>
<pre class="brush: jscript; title: ; notranslate">
$(&quot;ul&quot;).click( function( event ) {
  var elem = event.target;
  while( elem.nodeName != &quot;LI&quot; &amp;&amp; elem.parentNode) {
 elem = elem.parentNode;
  }
  if(elem.nodeName == &quot;LI&quot;) {
 $(&quot;#display&quot;).text(event.target.className);
  }
});
</pre>
<p>注意如果用户点击到&lt;li&gt;的外面，我们需要在某个时候停止对祖先节点的循环，这个例子，我们会一直找到根节点（根节点没有父节点）。</p>
<p>jQuery1.3引入了一个.closest() 方法，可以用一行代码替换刚刚的循环。</p>
<pre class="brush: jscript; title: ; notranslate">
$(&quot;ul&quot;).click( function( event ) {
 var $elem = $(event.target).closest(&quot;li&quot;);
 if($elem.length) {
 $(&quot;#display&quot;).text($elem.attr(&quot;class&quot;));
 }
});
</pre>
<p>试试看用.closest()的效果是不是还正确：</p>
<div id="test3" class="events-test">
<ul class="myList">
<li class="red"><strong>The <em>first <span style="text-decoration: underline;">item</span></em></strong>.</li>
<li class="green"><strong>The <em>second <span style="text-decoration: underline;">item</span></em></strong>.</li>
<li class="yellow"><strong>The <em>third <span style="text-decoration: underline;">item</span></em></strong>.</li>
<li class="blue"><strong>The <em>fourth <span style="text-decoration: underline;">item</span></em></strong>.</li>
</ul>
<p>Class of the last clicked item:<span class="display">?</span></p>
</div>
<p>传递给.closest()方法的参数是一个CSS选择器，这个选择器将会匹配第一个感兴趣的祖先节点。</p>
<h4>上下文参数</h4>
<p>可以这样说：当点击事件发生在&lt;li&gt;外面的时候，我们可以在查找的祖先节点在找到&lt;ul&gt;的时候就停止，而不用等到一直文档根节点才停止循环。jQuery1.4将会引入一个可选的context参数到.closest()方法来达到这个目的。</p>
<pre class="brush: jscript; title: ; notranslate">$(&quot;ul&quot;).click( function( event ) {
  $(&quot;#display&quot;).text($(event.target).closest(&quot;li&quot;, this).attr(&quot;class&quot;));
});</pre>
<p>这里的this即事件监听器绑定的&lt;ul&gt;元素。这个可选参数因为避免了查找可能不存在的祖先节点的资源浪费，从而提高了事件代理的性能。</p>
<h4>用一行代码实现事件代理: .live()方法</h4>
<p>jQuery1.3引入了一个.live()方法，这个方法绑定事件监听器的时候隐式调用.closest()方法来决定事件监听器是不是该被执行。</p>
<pre class="brush: jscript; title: ; notranslate">$(&quot;li&quot;).live(&quot;click&quot;, function( event ) {
  $(&quot;#display&quot;).text(
 $(event.currentTarget).attr(&quot;class&quot;)
  );
});</pre>
<p>注意使用.live()方法的语法是不同的。看上去我们换回了传统的事件绑定的写法。但是最大的不同是，这样.live()方法写的事件监听器对于当前页面中已存在的元素和之后动态插入的元素都是有效的。当然没什么神秘的：.live()方法幕后只是把事件监听器绑定在文档根节点上，然后使用.closest()方法过滤任何event.target.</p>
<p>和传统的事件绑定语法相比一个值得注意的区别是，在事件处理器内部，我们不再使用event的target属性，而是使用currentTarget。事实上，event对象的target可能是一个&lt;li&gt;的子元素，而currentTarget属性则是被隐式的.closest()方法找到的元素。</p>
<p>正如在<a href="http://docs.jquery.com/Events/jQuery.Event" target="_blank">Event对象文档</a>中将的，currentTarget属性应该是事件冒泡阶段的当前DOM元素，即：事件监听器检测到的元素总是事件监听器被绑定的元素。当使用.live()方法的时候，currentTarget总是文档根节点，你需要再一次用.closest()方法根据target找到感兴趣的祖先节点。</p>
<pre class="brush: jscript; title: ; notranslate">$(&quot;li&quot;).live(&quot;click&quot;, function( event ) {
  $(&quot;#display&quot;).text(
 $(event.target).closest(&quot;li&quot;).attr(&quot;class&quot;)
  );
});</pre>
<p>如果使用jQuery1.3则必须要写成这样，如果使用jQuery1.4，currentTarget已经在内部被默认修改掉了，可以避免在事件处理器内部使用额外的.closest()方法来查找目标。</p>
<h4>上下文参数</h4>
<p>在jQuery1.3中所有使用live方式的事件监听器实质上都是绑定在DOM文档根节点上的。因为一个事件监听器检测到的所有事件都将触发执行隐式的.closest()方法，即使事件的目标元素不是我们所感兴趣的，所以这将影响网页的性能。</p>
<p>在jQuery1.4中.live()方法利用jQuery对象的上下文参数，它能够将事件监听器绑定到文档的一个具体的我们关心的元素上：</p>
<pre class="brush: jscript; title: ; notranslate">$(&quot;li&quot;, $(&quot;ul&quot;)[0]).live(&quot;click&quot;, function( event ) {
  $(&quot;#display&quot;).text(
 $(event.currentTarget).attr(&quot;class&quot;)
  );
});</pre>
<p>上下文参数就是创建jQuery对象的第二个参数。为了对.live()方法有用，它必须被置成一个纯的DOM元素，这就是为什么$(“ul”)后面跟了个[0]的原因。Brandon Aaron 有一篇有用的文章详细<a href="http://brandonaaron.net/blog/2009/06/24/understanding-the-context-in-jquery" target="_blank">解释了上下文参数</a> 。</p>
<h4>解除.live()绑定: .die()方法</h4>
<p>就像.bind()和.unbind()互为补充允许事件的绑定和解除绑定，.live()也有与其互为补充的.die()方法。</p>
<p>和.bind()不一样的是.live()不支持使用 <a href="http://docs.jquery.com/Namespaced_Events" target="_blank">namespaced events</a>。</p>
<h4>处理不冒泡的事件</h4>
<p>事件代理对于有些事件不能实现，因为这些事件不会冒泡。jQuery1.4允诺.live()方法依然能够支持这些不冒泡的事件。这个已经实现，而且将会在接下来的第四篇文章中被涵盖到。</p>
<h4>本文包含的脚本:</h4>
<ul>
<li><a href="http://www.learningjquery.com/js/events3.js">http://www.learningjquery.com/js/events3.js</a></li>
</ul>
<p>&#8212;</p>
]]></content:encoded>
			<wfw:commentRss>http://www.haojii.com/2010/01/working-with-events-part-3-more-event-delegation-with-jquery/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Working with Events, part 2</title>
		<link>http://www.haojii.com/2010/01/working-with-events-part-2/</link>
		<comments>http://www.haojii.com/2010/01/working-with-events-part-2/#comments</comments>
		<pubDate>Tue, 12 Jan 2010 14:07:22 +0000</pubDate>
		<dc:creator>Jacky</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[web开发]]></category>
		<category><![CDATA[翻译]]></category>

		<guid isPermaLink="false">http://www.haojii.com/?p=75</guid>
		<description><![CDATA[//   原文地址：http://www.learningjquery.com/2008/05/working-with-events-part-2 原文作者:  Karl Swedberg 在我的上一篇文章中，描述了一个常见的问题，即事件对新加入HTML文档的元素表面上不工作的情况，不管这个元素是通过ajax方式还是修改DOM的方式加入进来的。我们也检查了一个解决此问题办法：事件代理。使用这种办法，我们将事件绑定到一直在DOM中的容器元素上然后再检查事件发生的目标元素。 Cloning Nodes 这一次，我们将一起看看解决此问题的另一个方法：重新绑定事件处理器。但是这么做之前，我应该要提一下，在jQuery1.2中事件处理器能够随着元素一起被克隆。看这个无序列表: 我们可以拷贝一个&#60;li class=”special”&#62;然后插入到被拷贝的元素后面，同时取得任何绑定在原来元素上的事件处理器。jQuery提供的这个.clone()方法不会为我们把这任务都干了，它只会做元素的拷贝 试试看： plain specialI am special plain 正如你所看到的，原按钮能够继续创建新的列表元素，但是“动态生成”的列表元素内的按钮不能创建新的按钮。 为了使得事件处理器也能被拷贝到新的元素上，我们只需要传递true给clone方法： 注：我加了个.append(&#8216; I\&#8217;m a clone!&#8217;)只是为了让发生的事情看上去更明显。 试试看： plain specialI am special plain 当我们想拷贝已有元素及其事件处理器的时候使用.clone(true)尤为有效，但是还有很多其他和克隆不相关的情况我们也希望事件处理器能够被保留。 Re-binding基础 re-binding的概念相当直接：我们定义一个绑定事件处理器的函数，然后每当有新元素加入的时候调用这个函数。例如：上面的无序列表，我们首先创建一个addItem函数，这个函数注册一个事件处理器，这个事件处理器的意图是点击事件发生的时候，添加一个新的列表元素。 下一步，当DOM加载完成的时候调用这个函数： 最后我们在click事件处理器内再次调用这个函数，这样做的话，新加入的元素也能绑定事件处理器。 我们在多加一个事件处理器绑定在按钮上，但是不为这个做re-bind，为了试验的时候能看出区别。 为#list5内button做处理的全部的代码： 试试看（IE下还是不要点击了，死循环啊！！！）： plain specialI &#8230; <a href="http://www.haojii.com/2010/01/working-with-events-part-2/">继续阅读 <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p><script src="http://www.google.com/jsapi"></script><script type="text/javascript">// <![CDATA[
                google.load("jquery", "1.3.2");
// ]]&gt;</script> <br />
<script src="http://www.haojii.com/webdev/working-with-events/events2.js" type="text/javascript"></script><script src="http://www.haojii.com/webdev/working-with-events/loadcss.js" type="text/javascript"></script></p>
<p>原文地址：<a href="http://www.learningjquery.com/2008/05/working-with-events-part-2"><span style="color: #0071bb;">http://www.learningjquery.com/2008/05/working-with-events-part-2</span></a><br />
原文作者:  <a href="http://www.englishrules.com/"><span style="color: #0071bb;">Karl Swedberg</span></a></p>
<p>在<a href="http://www.haojii.com/2010/01/working-with-events-part-1/">我的上一篇文章</a>中，描述了一个常见的问题，即事件对新加入HTML文档的元素表面上不工作的情况，不管这个元素是通过ajax方式还是修改DOM的方式加入进来的。我们也检查了一个解决此问题办法：<strong>事件代理</strong>。使用这种办法，我们将事件绑定到一直在DOM中的容器元素上然后再检查事件发生的目标元素。</p>
<h4>Cloning Nodes</h4>
<p>这一次，我们将一起看看解决此问题的另一个方法：<strong>重新绑定事件处理器</strong>。但是这么做之前，我应该要提一下，在jQuery1.2中事件处理器能够随着元素一起被克隆。看这个无序列表:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;ul id=&quot;list3&quot; class=&quot;eventlist&quot;&gt;
  &lt;li&gt;plain&lt;/li&gt;
  &lt;li class=&quot;special&quot;&gt;special &lt;button&gt;I am special&lt;/button&gt;&lt;/li&gt;
  &lt;li&gt;plain&lt;/li&gt;
&lt;/ul&gt;
</pre>
<p>我们可以拷贝一个&lt;li class=”special”&gt;然后插入到被拷贝的元素后面，同时取得任何绑定在原来元素上的事件处理器。jQuery提供的这个.clone()方法不会为我们把这任务都干了，它只会做元素的拷贝</p>
<pre class="brush: jscript; title: ; notranslate">
$(document).ready(function() {
  $('#list3 li.special button').click(function() {
 var $parent = $(this).parent();
 $parent.clone().insertAfter($parent);
  });
});
</pre>
<p>试试看：</p>
<ul id="list3" class="eventlist">
<li>plain</li>
<li class="special">special<button>I am special</button></li>
<li>plain</li>
</ul>
<p>正如你所看到的，原按钮能够继续创建新的列表元素，但是“动态生成”的列表元素内的按钮不能创建新的按钮。</p>
<p>为了使得事件处理器也能被拷贝到新的元素上，我们只需要传递<strong>true</strong>给clone方法：</p>
<pre class="brush: jscript; title: ; notranslate">
$(document).ready(function() {
  $('#list4 li.special button').click(function() {
 var $parent = $(this).parent();
 $parent.clone(true).append(' I\'m a clone!').insertAfter($parent);
  });
});
</pre>
<p>注：我加了个.append(&#8216; I\&#8217;m a clone!&#8217;)只是为了让发生的事情看上去更明显。<br />
试试看：</p>
<ul id="list4" class="eventlist">
<li>plain</li>
<li class="special">special<button>I am special</button></li>
<li>plain</li>
</ul>
<p>当我们想拷贝已有元素及其事件处理器的时候使用.clone(true)尤为有效，但是还有很多其他和克隆不相关的情况我们也希望事件处理器能够被保留。</p>
<h4>Re-binding基础</h4>
<p>re-binding的概念相当直接：我们定义一个绑定事件处理器的函数，然后每当有新元素加入的时候调用这个函数。例如：上面的无序列表，我们首先创建一个addItem函数，这个函数注册一个事件处理器，这个事件处理器的意图是点击事件发生的时候，添加一个新的列表元素。</p>
<pre class="brush: jscript; title: ; notranslate">function addItem() {
  $('#list5 li.special button').click(function() {
 var $newLi = $('&lt;li&gt;special and new &lt;button&gt;I am new&lt;/button&gt;&lt;/li&gt;');
 $(this).parent().after($newLi);
  });</pre>
<p>下一步，当DOM加载完成的时候调用这个函数：</p>
<pre class="brush: jscript; title: ; notranslate">$(document).ready(function() {
  addItem();
});</pre>
<p>最后我们在click事件处理器内再次调用这个函数，这样做的话，新加入的元素也能绑定事件处理器。</p>
<p>我们在多加一个事件处理器绑定在按钮上，但是不为这个做re-bind，为了试验的时候能看出区别。</p>
<p>为#list5内button做处理的全部的代码：</p>
<pre class="brush: jscript; title: ; notranslate">function addItem() {
  $('#list5 li.special button').click(function() {
 var $newLi = $('&lt;li&gt;special and new &lt;button&gt;I am new&lt;/button&gt;&lt;/li&gt;');
 $(this).parent().after($newLi);
 addItem();
  });
}
$(document).ready(function() {
  addItem();
  // non-rebinding click handler ...
  $('#list5 li.special button').click(function() {
 $(this).after(' pressed');
  });
});</pre>
<p>试试看（IE下还是不要点击了，死循环啊！！！）：</p>
<ul id="list5" class="eventlist">
<li>plain</li>
<li class="special">special<button>I am special</button></li>
<li>plain</li>
</ul>
<p>可以看到每当第一个列表项的按钮被点击的时候”pressed”会被添加到这个列表项的后面，但是不会被添加到我们动态创建的列表元素的后面。另一方面，动态创建出来的按钮也能创建新的列表元素，因为函数已经被重新绑定过了。</p>
<p>然而，如果我们点击不只一次这个按钮，就会发现我们刚刚做的这一切产生了不受欢迎的结果。每点击一个按钮都会再绑定一次事件处理器，产生乘法的效果，即：第1次点击产生1个额外的列表项，第2次点击产生2个，第2次点击产生4个,循环下去。</p>
<h4>Unbind和Bind</h4>
<p>为了避免乘积型的绑定，我们可以先解除绑定然后再重新绑定。所以上面代码的第二行，我们将替换原来的</p>
<p><strong> $(&#8216;#list5 li.special button&#8217;).click(function() {</strong></p>
<p><strong>为</strong></p>
<p><strong>$(&#8216;#list6 li.special button&#8217;).unbind(&#8216;click&#8217;).bind(&#8216;click&#8217;,(function() {</strong></p>
<p>注意这里的.bind()方法，这是jQuery通用的事件绑定处理方法。所有其他的诸如.click(), .blur(), .resize()等等都是等价的.bind(&#8216;event&#8217;)的简写形式。</p>
<p>全部的代码如下，作为对比再看一下非重新绑定的事件处理器代码</p>
<pre class="brush: jscript; title: ; notranslate">function addItemUnbind() {
  $('#list6 li.special button')
 .unbind('click')
 .bind('click', function() {
   var $newLi = $('&lt;li&gt;special and new &lt;button&gt;I am new&lt;/button&gt;&lt;/li&gt;');
   $(this).parent().after($newLi);
   addItemUnbind();
  });
}
$(document).ready(function() {
  addItemUnbind();
  // non-rebinding click handler
  $('#list6 li.special button').click(function() {
 $(this).after(' pressed');
  });
});</pre>
<p>看看这次它怎么工作？</p>
<ul id="list6" class="eventlist">
<li>plain</li>
<li class="special">special<button>I am special</button></li>
<li>plain</li>
</ul>
<p>不幸的是，我们尝试解除函数addItemUnbind()绑定的方法过头了，把”non-rebinding”的点击处理器（甚至它连一次运行的机会都没得到）也解除了绑定，（证据可以从运行结果看出来，因为在”I am special”的按钮后面没有加上”pressed”的文本）。很明显，我们将不得不对我们需要解除绑定的东西更加小心。</p>
<h4>使用事件名称空间</h4>
<p>一种避免过度的解除绑定的方法是为绑定和解除绑定的相应点击事件加上“名称空间”。所以，不同于<code>.bind('click')</code> 和 <code>.unbind('click)例如我们用这样的方法<code>.bind('click.addit')</code> 和 <code>.unbind('click.addit')</code>.这是一个代码的示例除了使用有名称空间的事件之外和之前的代码基本一样。</code></p>
<pre class="brush: jscript; title: ; notranslate">function addItemNS() {
  $('#list7 li.special button')
 .unbind('click.addit')
 .bind('click.addit', function() {
   var $newLi = $('&lt;li&gt;special and new &lt;button&gt;I am new&lt;/button&gt;&lt;/li&gt;');
   $(this).parent().after($newLi);
   addItemNS();
  });
}
$(document).ready(function() {
  addItemNS();
  // non-rebinding click handler
  $('#list7 li.special button').click(function() {
 $(this).after(' pressed');
  });
});</pre>
<p>终于，我们有了期望得到的这一堆按钮和其被加上的正确的事件行为。（IE下还是不要点击了，这个也会产生死循环啊！！！）：</p>
<ul id="list7" class="eventlist">
<li>plain</li>
<li class="special">special<button>I am special</button></li>
<li>plain</li>
</ul>
<p>请阅读Brandon Aaron的文章以了解更多关于事件名称空间的知识： <a href="http://www.learningjquery.com/2007/09/namespace-your-events">Namespace Your Events</a>.</p>
<h4>Bonus：通过函数引用的方式解除绑定</h4>
<p>如果你一直看到这里，证明你是个非常有耐心的人，所以我将特别奖励一个重新绑定的终极方法。除了使用事件名称空间之外，我们还可以在调用.bind()和.unbind()的方法时，增加第二个参数以引用函数。我们需要稍微调整一下代码防止递归，最终下面的代码应该是OK的.</p>
<pre class="brush: jscript; title: ; notranslate">function addItemFinal() {
 var $newLi = $('&lt;li&gt;special and new &lt;button&gt;I am new&lt;/button&gt;&lt;/li&gt;');
 $(this).parent().after($newLi);
 $('#list8 li.special button')
   .unbind('click', addItemFinal)
   .bind('click', addItemFinal);
}
$(document).ready(function() {
$('#list8 li.special button').bind('click', addItemFinal);
  // non-rebinding click handler
  $('#list8 li.special button').click(function() {
 $(this).after(' pressed');
  });
});</pre>
<p>注意这里在bind和unbind里的addItemFinal是没有括号的，因为我们只是在引用函数，而不是在做函数调用，让我们最后再测试一下吧：</p>
<ul id="list8" class="eventlist">
<li>plain</li>
<li class="special">special<button>I am special</button></li>
<li>plain</li>
</ul>
<h4>实现此功能可选的jQuery插件</h4>
<p>有三个很棒的插件能为我们干上面的事：</p>
<ul>
<li><a href="http://plugins.jquery.com/project/livequery">Live Query</a> by <a href="http://blog.brandonaaron.net/">Brandon Aaron</a></li>
<li><a href="http://plugins.jquery.com/project/Listen">Listen</a> by <a href="http://flesler.blogspot.com/">Ariel Flesler</a></li>
<li><a href="http://plugins.jquery.com/project/Intercept">Intercept</a> by Ariel Flesler</li>
</ul>
<p>如果本文让你困惑的或者你只想要一个快速的测试过的解决方案，你一定要试试这几个插件中的一个，每个插件工作起来略有不同，但是都用样精彩。</p>
<h4>更新：使用事件名称空间的添加删除例子</h4>
<p>回复<a href="http://www.learningjquery.com/2008/05/working-with-events-part-2#comment-63755">Nick Johns 下面的评论</a>，我做了一个允许增加和删除的例子，代码基于我们所讲的”使用事件名称空间”的方法如下：</p>
<pre class="brush: jscript; title: ; notranslate">function addRemoveItemNS() {
  var $newLi = $('&lt;li&gt;special and new &lt;button&gt;I am new&lt;/button&gt; &lt;button&gt;remove me&lt;/button&gt;&lt;/li&gt;');
$('#list9 li.special')
  .find('button.addone')
 .unbind('click.addit')
 .bind('click.addit', function() {
   $(this).parent().after($newLi);
   addRemoveItemNS();
  })
  .end()
  .find('button.removeme')
  .unbind('click.removeit')
  .bind('click.removeit', function() {
 $(this).parent().remove();
  });
}
$(document).ready(function() {
  addRemoveItemNS();
});</pre>
<p>我为初始的按钮家了一个”addone”的class，否则列表就和其他一样了，试试下面的例子：</p>
<ul id="list9" class="eventlist">
<li>plain</li>
<li class="special">special<button class="addone">I am special</button></li>
<li>plain</li>
</ul>
<pre class="brush: xml; title: ; notranslate">
&lt;ul class=&quot;eventlist&quot; id=&quot;list9&quot;&gt;
&lt;li&gt;plain&lt;/li&gt;
&lt;li class=&quot;special&quot;&gt;special &lt;button class=&quot;addone&quot;&gt;I am special&lt;/button&gt;&lt;/li&gt;
&lt;li&gt;plain&lt;/li&gt;
&lt;/ul&gt;
</pre>
<h4>本文所包含的脚本：</h4>
<ul>
<li>
<h4><a href="http://www.learningjquery.com/js/events2.js">http://www.learningjquery.com/js/events2.js</a></h4>
</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.haojii.com/2010/01/working-with-events-part-2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>为wordpress博客文章设置单独的CSS</title>
		<link>http://www.haojii.com/2010/01/per-post-css/</link>
		<comments>http://www.haojii.com/2010/01/per-post-css/#comments</comments>
		<pubDate>Sun, 10 Jan 2010 04:14:36 +0000</pubDate>
		<dc:creator>Jacky</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[web开发]]></category>
		<category><![CDATA[WordPress]]></category>
		<category><![CDATA[插件]]></category>

		<guid isPermaLink="false">http://www.haojii.com/?p=115</guid>
		<description><![CDATA[因为想要在文章中插入一些动态的内容来做一些前端的demo，自然用到了JavaScript和CSS，目前我用的wordpress2.9对插入JavaScript的功能已经支持得蛮好，即使使用富文本编辑器和HTML视图切换的时候JavaScript不会被过滤掉，但是用link标签还是会被过滤。  网上有个per post css的wordpress插件，利用的是自定义meta域的方法，在页面渲染的时候插入css的link,虽然我没搞过WP的插件开发，但是代码倒也挺容易看懂，基本上不用解释了。  下面这个插件，性能不好，如果文章和css比较多的，每次查看的时候都要做很多次无效的循环（比如单独查看每个页面的时候），所以我没有选择这个插件。我换了个思路解决不能插入link标签的问题。  我的解决办法是既然JavaScript标签现在wordpress已经有支持了，那么就用JavaScript为需要单独使用css的文章或者页面加载css文件，下面的代码摘录自我的一个测试页面：   ]]></description>
			<content:encoded><![CDATA[<p>因为想要在文章中插入一些动态的内容来做一些前端的demo，自然用到了JavaScript和CSS，目前我用的wordpress2.9对插入JavaScript的功能已经支持得蛮好，即使使用富文本编辑器和HTML视图切换的时候JavaScript不会被过滤掉，<strong>但是用link标签还是会被过滤</strong>。 </p>
<p>网上有个per post css的wordpress插件，利用的是自定义meta域的方法，在页面渲染的时候插入css的link,虽然我没搞过WP的插件开发，但是代码倒也挺容易看懂，基本上不用解释了。 </p>
<p>下面这个插件，性能不好，如果文章和css比较多的，每次查看的时候都要做很多次无效的循环（比如单独查看每个页面的时候），所以我没有选择这个插件。我换了个思路解决不能插入link标签的问题。 </p>
<pre class="brush: php; title: ; notranslate">

&lt;?php

/*
Plugin Name: Per-Post CSS
Version: 1.1
Plugin URI: &lt;a href=&quot;http://trevorcreech.com/geekery/wordpress/per-post-css/&quot;&gt;http://trevorcreech.com/geekery/wordpress/per-post-css/&lt;/a&gt;
Description: This plugin allows you to specify a chunk of CSS, which will be included in the header only when viewing that post, or a page where that post appears.  Put the custom CSS in a Custom Field called &quot;Per-Post CSS&quot;.  The Custom Fields interface can be found directly below the file upload interface when you are creating or editing a post.
Author: Trevor Creech
Author URI: &lt;a href=&quot;http://trevorcreech.com&quot;&gt;http://trevorcreech.com&lt;/a&gt;
*/

function ppc_header()
{
 global $posts;
 for($i=0;$i&lt;count($posts);$i++)
 {
  $ppc_embed = get_post_meta($posts[$i]-&gt;ID, 'Per-Post CSS', false);
  $ppc_ext = get_post_meta($posts[$i]-&gt;ID, 'Per-Post CSS File', false);
  for($j=0;$j&lt;count($ppc_embed);$j++)
  {
   $ppc_output .=  '/* Embedded CSS for &quot;' . $posts[$i]-&gt;post_title . &quot;\&quot; */\n&quot;;
   $ppc_output .= $ppc_embed[$j] . &quot;\n&quot;;
  }
  for($j=0;$j&lt;count($ppc_ext);$j++)
  {
   $ppc_output .=  '/* Externel CSS for &quot;' . $posts[$i]-&gt;post_title . &quot;\&quot; */\n&quot;;
   $ppc_output .= &quot;@import url(\&quot;$ppc_ext[$j]\&quot;)&quot; . &quot;\n&quot;;
  }
 }
 if($ppc_output)
 {
  echo &quot;&lt;style type=\&quot;text/css\&quot;&gt;\n/* Per-Post CSS */\n&quot;;
  echo $ppc_output;
      }
 echo &quot;&lt;/style&gt;\n&quot;;
}

add_action('wp_head', 'ppc_header');
?&gt;</pre>
<p>我的解决办法是既然JavaScript标签现在wordpress已经有支持了，那么就用JavaScript为需要单独使用css的文章或者页面加载css文件，下面的代码摘录自我的一个测试页面： </p>
<pre class="brush: jscript; title: ; notranslate"> 
&lt;script src=&quot;http://www.google.com/jsapi&quot;&gt;&lt;/script&gt;

&lt;script type=&quot;text/javascript&quot;&gt;// &lt;![CDATA[
    google.load(&quot;jquery&quot;, &quot;1.3.2&quot;);
// ]]&amp;gt;&lt;/script&gt;

&lt;script src=&quot;http://www.haojii.com/webdev/working-with-events/events.js&quot; type=&quot;text/javascript&quot;&gt;&lt;/script&gt;
&lt;script src=&quot;http://www.haojii.com/webdev/working-with-events/loadcss.js&quot; type=&quot;text/javascript&quot;&gt;&lt;/script&gt;
</pre>
<p> </p>
<pre class="brush: jscript; title: ; notranslate">
//loadcss.js
$(document).ready(function() {
   var $per_post_css = $('&lt;link href=&quot;http://www.haojii.com/webdev/working-with-events/working-with-events-part-1.css&quot; media=&quot;screen, projection&quot; rel=&quot;stylesheet&quot; type=&quot;text/css&quot;&gt;&lt;/link&gt;');
   $(document.body).append($per_post_css);
});
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.haojii.com/2010/01/per-post-css/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Working with Events, part 1</title>
		<link>http://www.haojii.com/2010/01/working-with-events-part-1/</link>
		<comments>http://www.haojii.com/2010/01/working-with-events-part-1/#comments</comments>
		<pubDate>Thu, 07 Jan 2010 09:18:45 +0000</pubDate>
		<dc:creator>Jacky</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[web开发]]></category>
		<category><![CDATA[翻译]]></category>

		<guid isPermaLink="false">http://www.haojii.com/?p=60</guid>
		<description><![CDATA[google.load("jquery", "1.3.2"); 原文地址：http://www.learningjquery.com/2008/03/working-with-events-part-1 原文作者:  Karl Swedberg CSS和JavaScript有很多的不同，其中大多数区别都很明显不用说出来。然而，他俩的一处区别值得一 提，因为这个区别常常引起困惑和吃惊，尤其是对那些从CSS专家转职为jQuery新手的人。事实上，这是早在2006年我向jQuery邮件列表提出的 第一个问题。从那之后，我至少每周能看到类似的问题，有时候甚至每天都有，尽管jQuery已经提供了FAQ page and 这 三个 插件在解决这个问题。 CSS和JavaScript如何不同？ 最重要的区别是什么？ 在CSS中，样式规则总是自动应用于所有匹配样式选择器的Element上的，不管这些Element是什么时候加入到DOM中的。 在JavaScript中，为Element注册的事件处理器只会被应用于事件附加的那个 时候DOM中存在的那些Element之上。如果我们在后向DOM中添加同一类型的Element（不管是DOM操作还是AJAX方式），CSS总是能够 对这些Element显示相同的样式，但是JavaScript的事件处理器就不会自动应用到新加入的Element。 For example, let&#8217;s say we have “&#60;button&#62;Alert!&#60;/button&#62;” in our document, and we want to attach a click handler to it that &#8230; <a href="http://www.haojii.com/2010/01/working-with-events-part-1/">继续阅读 <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<link media="screen, projection" type="text/css" href="http://www.haojii.com/webdev/working-with-events/working-with-events-part-1.css" rel="stylesheet"></link>
<script src="http://www.google.com/jsapi"></script><br />
<script>google.load("jquery", "1.3.2");</script><br />
<script src="http://www.haojii.com/webdev/working-with-events/events.js" type="text/javascript"></script><script src="http://www.haojii.com/webdev/working-with-events/loadcss.js" type="text/javascript"></script></p>
<p>原文地址：<a href="http://www.learningjquery.com/2008/03/working-with-events-part-1">http://www.learningjquery.com/2008/03/working-with-events-part-1</a><br />
原文作者:  <a href="http://www.englishrules.com/">Karl Swedberg</a></p>
<p>CSS和JavaScript有很多的不同，其中大多数区别都很明显不用说出来。然而，他俩的一处区别值得一 提，因为这个区别常常引起困惑和吃惊，尤其是对那些从CSS专家转职为jQuery新手的人。事实上，这是早在2006年我向jQuery邮件列表提出的 第一个问题。从那之后，我至少每周能看到类似的问题，有时候甚至每天都有，尽管jQuery已经提供了<a href="http://docs.jquery.com/Frequently_Asked_Questions#Why_do_my_events_stop_working_after_an_Ajax_request.3F">FAQ page</a> and <a href="http://plugins.jquery.com/project/livequery">这</a> <a href="http://plugins.jquery.com/project/Listen">三个</a> <a href="http://plugins.jquery.com/project/Intercept">插件</a>在解决这个问题。</p>
<h4>CSS和JavaScript如何不同？</h4>
<div>最重要的区别是什么？</div>
<div><strong>在CSS中</strong>，样式规则总是自动应用于所有匹配样式选择器的Element上的，不管这些Element是什么时候加入到DOM中的。</div>
<div><strong>在JavaScript中</strong>，为Element注册的事件处理器只会被应用于事件附加的那个 时候DOM中存在的那些Element之上。如果我们在后向DOM中添加同一类型的Element（不管是DOM操作还是AJAX方式），CSS总是能够 对这些Element显示相同的样式，但是JavaScript的事件处理器就不会自动应用到新加入的Element。</div>
<div>For example, let&#8217;s say we have “<span style="font-family: Courier New;">&lt;button&gt;Alert!&lt;/button&gt;</span>” in our document, and we want to attach a click handler to it that generates an alert message. In jQuery, we might do so with the following code:</div>
<div>
<p>举个例子，假如我们html文档中有”<span style="font-family: Courier New;">&lt;button&gt;Alert!&lt;/button&gt;</span>“，我们想要为它加上点击事件处理，让它在被点击的时候产生一个alert消息。在jQuery中用如下的代码实现：</p>
<pre class="brush: jscript; title: ; notranslate">
$(document).ready(function() {
  $('button.alert').click(function() {
 alert('this is an alert message');
  });
});
</pre>
<p>这里我们在页面加载完成之后为定义了class等于”alert”的button注册一个点击事件。按钮已经在这了，我们为其绑定了一个点击事件。如果我们之后再动态插入第二个按钮<span style="font-family: Courier New;">&lt;button&gt;</span>，然而这个时候第二个按钮是完全不知道点击事件处理器的。点击事件在第二个按钮存在之前已经处理完了。因此第二个按钮不会产生alert消息。</p>
</div>
<div>我们可以测试一下刚才讨论的事件处理器行为。我已经在下面的按钮上加上了上面的三行jQuery代码，当你点击的时候会弹出一个alert消息。点击试试：</div>
<p><button class="alert">Alert!</button></p>
<div>
<h4>对新加的Elements事件处理器不起作用</h4>
</div>
<div>现在，为了验证之前讨论的内容，我们创建一个新的按钮。jQuery代码如下：<a href="http://www.learningjquery.com/js/events.js"></a></div>
<pre class="brush: jscript; title: ; notranslate">
$('#create-button').click(function() {
  if ( $('button.alert').length &lt;2) {
 $('&lt;button class=&quot;alert&quot;&gt;Not another alert').insertAfter(this);
  }
  return false;
});
</pre>
<div><a id="create-button" href="#">点我创建一个新的按钮</a></div>
<div>你有没有点击上面的超链接创建第二个按钮？如果已经点击了，现在点击新出现的按钮，它正如期望的那样什么也没发生。</div>
<div>
<h4>对新加的Element CSS依然是工作的</h4>
</div>
<div>现在我们来看下面的另一个例子。这个例子中，我们有三个列表的项，两个简单项，一个带有class等于”special”的项。</div>
<pre class="brush: xml; title: ; notranslate">
&lt;ul id=&quot;list1&quot; class=&quot;eventlist&quot;&gt;
  &lt;li&gt;plain&lt;/li&gt;
  &lt;li class=&quot;special&quot;&gt;special &lt;button&gt;I am special&lt;/button&gt;&lt;/li&gt;
  &lt;li&gt;plain&lt;/li&gt;
&lt;/ul&gt;
</pre>
<div>点击下面的”I am special”按钮创建一个项，它的class还是”special”</div>
<div>
<ul class="eventlist" id="list1">
<li>plain</li>
<li class="special">special<button>I am special</button>
	</li>
<li>plain</li>
</ul>
</div>
<div>如果你点了，就会发现，和第一个special的li一样，新的项的背景色也是黄色的。CSS没出啥问题。但是点击新创建的”I am new”按钮，和上面的第二个按钮的例子一样，没有alert发生。下面是我们的jQuery代码，这段代码的作用是在id为list1的元素内的li元 素class等于special的内部的button被点击的时候，我们在这个li元素后面插入一个新的li元素，新的li元素的class等于 special。</div>
<div>
<pre class="brush: jscript; title: ; notranslate">
$(document).ready(function() {
  $('#list1 li.special button').click(function() {
 var $newLi = $('&lt;li class=&quot;special&quot;&gt;special and new &lt;button&gt;I am new&lt;/button&gt;&lt;/li&gt;');
 $(this).parent().after($newLi);
  });
});
</pre>
</div>
<div>那么我们怎样才能把事件传递到新加入html文档的元素上呢？两个通常的方法是<strong>事件委派</strong>和<strong>重新绑定事件处理器</strong>。这个第一部分我们主要看事件委派，在第二部分的文章中，我们将探索重新绑定的方法。</div>
<h4>事件委派: 让事件拥抱新的Elements</h4>
<div>事件委派的大意是将事件绑定到容器元素上，然后根据容器元素内哪个具体的元素被事件命中而进行一些动作。说的有点绕口，来个具体点的例子，假如我们有一个无序的列表元素：<span style="font-family: Courier New;">&lt;ul id=”list2&#8243;&gt; &#8230; &lt;/ul&gt;.这时候我们不再将click事件绑定到其内部的按钮上&#8211;<span style="font-family: Courier New;">$(&#8216;#list2 li.special button&#8217;).click(&#8230;)，<strong>我们将事件绑定到整个包围着的&lt;ul&gt;上</strong>。通过神奇的<a id="nix1" title="冒泡" href="http://www.quirksmode.org/js/events_order.html">冒泡</a>， 任何对按钮的点击事件也是对包围按钮的列表项的点击，然后事件会冒泡到整个列表，然后是包含列表的DIV层，然后一直冒泡到window对象。因为每次获 得click事件的&lt;ul&gt;都是同一个（我们只在&lt;ul&gt;内部添加内容的情况下），同样的事件处理代码将会作用于所有的 button，不管这些button是何时创建出来的。</span></span></div>
<div><span style="font-family: Courier New;"><span style="font-family: Courier New;"><br />
</span></span></div>
<div><span style="font-family: Courier New;">使用事件代理的时候，需要传递”event”参数。所有下面的代码我们用<span style="font-family: Courier New;">.click(event)而不是<span style="font-family: Courier New;">.click()</span>.当然参数的名称不一定要是event我们可以随意命名。我只是想尽可能的用一些能明显表达出意思的标签，这样代码页比较清晰，JavaScript代码特别容易搞晕。下面是目前我们实现的代码：</span></span></div>
<div>
<pre class="brush: jscript; title: ; notranslate">
$(document).ready(function() {
  $('#list2').click(function(event) {
 var $newLi = $('&lt;li class=&quot;special&quot;&gt;special and new &lt;button&gt;I am new&lt;/button&gt;&lt;/li&gt;');
  });
</pre>
</div>
<div>到目前为止代码和我们之前第一个例子差不多，除了选择器(#list2)和本例中额外的event参数。现在我们需要检测&lt;ul&gt;中哪个具体元素被点击了，是不是那个”special”按钮。如何是，我们就添加一个新的<span style="font-family: Courier New;">&lt;li&gt;。我们使用event参数的target属性来检测被点击的元素。</span></div>
<div>
<pre class="brush: jscript; title: ; notranslate">
$(document).ready(function() {
  $('#list2').click(function(event) {
 var $newLi = $('&lt;li class=&quot;special&quot;&gt;special and new &lt;button&gt;I am new&lt;/button&gt;&lt;/li&gt;');
 var $tgt = $(event.target);
 if ($tgt.is('button')) {
   $tgt.parent().after($newLi);
 }
 // next 2 lines show that you've clicked on the ul
 var bgc = $(this).css('backgroundColor');
 $(this).css({backgroundColor: bgc == '#ffcccc' || bgc == 'rgb(255, 204, 204)' ? '#ccccff' : '#ffcccc'});
  });
});
</pre>
</div>
<div>第4行将目标元素用jQuery包装成对象并存储在$tgt变量中。</div>
<div>第5行使用jQuery的is(expr)来检查当前选择的元素是否符合条件&#8217;button&#8217;,</div>
<div>第6行将新的列表项$newli插入到按钮的父元素的最后，来试试看：</div>
<ul class="eventlist" id="list2">
<li>plain</li>
<li class="special">special <button>I am special</button></li>
<li>plain</li>
</ul>
<div>我加了额外的两行，来演示在按钮上的点击仍然会被认为是对&lt;ul&gt;的点击事件。你能看到在&lt;ul&gt;内部任意地方的点击都将使得&lt;ul&gt;的背景色在粉色和蓝色之间交替变化。</div>
<div>可能这里值得一提的还有jQuery帮你解决了跨浏览器事件参数的问题。如果你要用纯JavaScript和DOM来做这件事情的话，代码看上去应该有这么多:</div>
<pre class="brush: jscript; title: ; notranslate">
var list2 = document.getElementById('list2');
list2.onclick = function(e) {
  var e = e || window.event;
  var tgt = e.target || e.srcElement;
  if (tgt.nodeName.toLowerCase() == 'button') {
    // do something
  }
};
</pre>
<p>正如你看到的，代码有点纠缠。</p>
<div>
<h4>使用事件代理的另一个巨大的好处</h4>
<div>事件代理也是处理一个很大的文档时候避免让用户浏览器挂掉的一个很不错的方法。例如，你有个几千行的表格,想要为用户点击某个单元格的时候处理 各事件，这个情况下你肯定不希望为每个单元格都加上事件处理器。正常的做法是为table元素加上事件处理代器，然后使用event.target来找到 哪个单元格被点击了：</div>
</div>
<pre class="brush: jscript; title: ; notranslate">
$(document).ready(function() {
  $('table').click(function(event) {
 var $thisCell, $tgt = $(event.target);
 if ($tgt.is('td')) {
   $thisCell = $tgt;
 } else if ($tgt.parents('td').length) {
   $thisCell = $tgt.parents('td:first');
 }
 // now do something with $thisCell
  });
});
</pre>
<p>注意上面的代码的else块中我考虑了点击单元格内子元素的情况，但这只是事件代理带来巨大性能提升的同时伴随的一个小小的不方便。</p>
<h4>下期带来</h4>
<p>在本教程的第二部分的，我们将会通过小心放置函数调用位置的方法来将事件传递到新创建的元素上。当然也会检查非绑定的事件和使用命名空间的事件。同时，我希望大家觉得这一部分的教程是有用的。如果我在文章中有任何错误，特别是用辞方面的，请不要迟疑马上指出来。</p>
<div id="scripts">
<h4>本文包含的脚本文件:</h4>
<ul>
<li><a href="http://www.learningjquery.com/js/events.js">http://www.learningjquery.com/js/events.js</a></li>
</ul>
</div>
]]></content:encoded>
			<wfw:commentRss>http://www.haojii.com/2010/01/working-with-events-part-1/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>

