第二个示例Web应用程序
我将使用另一个小部件解决本文的最后3个问题,并且在深入研究其代码之前展示和解释它。这个401k小部件并不陌生,因为您已经在前面的文章见过它(参见参考资料部分获取这些文章的链接)。不过,这回有个微妙的不同之处,因为我在同一个页面上两次添加了这个小部件。它被添加到两个不同的表中。这将带来几个有趣的地方。图3显示了这个小部件:
在这个小部件中,我正在做几件事情。第一件是计算文本字段之和并确定它们是否为100。如果它们的和不为100,我将向用户显示一个错误,提示他们没有正确使用该小部件。第二,我在每个选项获取输入之后对选项进行排序。通过这种方式,百分比最高的投资分配将一直出现在表的顶部。这可以在图3中看到,它按百分比对选项进行排序。最后,为了让它更酷,我添加了一些条带。
用于生产这个小部件的HTML代码出奇地简单。清单8详细地显示了这个小部件。
- <p><tablewidthtablewidth=300class="percentSort"cellpadding=0cellspacing=0>
- <tbody>
- <tr><td>S&P500Index</td>
- <td><inputtypeinputtype=text>%</td></tr>
- <tr><td>Russell2000Index</td>
- <td><inputtypeinputtype=text>%</td></tr>
- <tr><td>MSCIInternationalIndex</td>
- <td><inputtypeinputtype=text>%</td></tr>
- <tr><td>MSCIEmergingMarketIndex</td>
- <td><inputtypeinputtype=text>%</td></tr>
- <tr><td>REITIndex</td>
- <td><inputtypeinputtype=text>%</td></tr>
- </tbody>
- <tfoot>
- </tfoot>
- </table>
用jQuery设置小部件
以上的一小段HTML直接引入了这部分内容,本小节关注如何在jQuery中设置小部件,以及所需的所有代码。要将事件附加到页面元素或在特定情况下需要添加类时,通常需要这样做。有时候还需要更进一步。这些小部件的所有设置代码都是jQuery代码。
我可以提供关于角色分离的理论,让HTML设计师和JavaScript程序员各自完成自己的工作,但是您们可能已经多次听到这种陈词。在这里我仅添加另一样东西,即“类修饰”,这是很多插件创作者都使用的。看看清单8中的HTML代码,仅通过将一个percentSort类添加到表,您就可以显著改变表的功能和外观。这是小部件设计的目标,让添加和删除小部件就像向小部件添加类一样简单。
让我们遵循我曾用jQuery设置小部件的几个步骤。通过查看这些步骤,您可以看到清单9中的设计模式是如何出现的。
- $(document).ready(function(){
- //thefirststepistofindallthetablesonthepagewith
- //aclassofpercentSort.Theseareallthetableswewantto
- //convertintoourwidget.
- //Afterwefindthem,weneedtoloopthroughthemandtakesome
- //actionsonthem
- //Attheconclusionofthisblockofcode,eachtablethat'sgoingto
- //beapercentSortwidgetwillhavebeentransformed
- $("table.percentSort").each(function(i){
- //eachtableneedsauniqueID,fornamespaceissues(discussedlater)
- //wecansimplycreateauniqueIDfromtheloopcounter
- $(this).attr("id","percentSort-"+i);
- //withineachtable,let'shighlighteveryotherrowinthetable,to
- //giveitthat"zebra"look
- $(this).find("tbody>tr").filter(":odd").addClass("highlight");
- //becauseeachtableneedstoshowthe"Total"totheuser,let'screateanew
- //sectionofthetableinthefooter.We'lladdarowinthetablefooter
- //todisplaythewords"Total"andaspanfortheupdatedcount.
- $("#"+$(this).attr("id")+"tfoot")
- .append("<tr><td>Total</td><td>
- <span></span>%</td></tr>");
- //finally,let'saddtheCLASSof"percentTotal"tothespanwejust
- //createdabove.We'llusethisinformationlatertodisplay
- //theupdatedtotals
- $("#"+$(this).attr("id")+"tfootspan").addClass("percentTotal");
- });
- //nowthesecondstep,afterwe'vecompletedsettingupthetablesthemselves
- //istosetuptheindividualtablerows.
- //Wecansimilarlysortthrougheachofthem,takingtheappropriateactions
- //oneachoftheminturn.
- //Uponcompletionofthisblockofcode,eachrowineachtablewillbe
- //transformedforourwidget
- $("table.percentSorttbody>tr").each(function(i){
- //getthenamespace(tobediscussedinthenextsection)
- varNAMESPACE=$(this).parents("table.percentSort").attr("id");
- //attachauniqueIDtothisrow.Wecanusetheloopcounter
- //toensuretheIDisuniqueonthepage(whichisamustoneverypage)
- $(this).attr("id","row"+i);
- //now,withinthisrowofthetable,weneedtofindthetextinput,because
- //weneedtoattachaclasstothem.Weutilizethenamespace,andalso
- //findthe:textwithinthetablerow,andthenattachthecorrectclass
- $("#"+$(this).attr("id")+":text").addClass("percent");
- //Finally,weattachauniqueIDtoeachofthetextinputs,andwedothisby
- //makingitacombinationofthetablenameandtherowname.
- $("#"+$(this).attr("id")+".percent").
- attr("id",NAMESPACE+"-"+$(this).attr("id"));
- });
- //Finally,becauseweknowweonlywantnumericalinputs,werestrictthetextentry
- //tojustnumbers.Wemustdothisnow,becauseupuntilthispoint,thepage
- //containednoelementswiththeCLASS"percent"
- $(".percent").numeric();
如您从这个例子中见到的一样,可以通过jQuery代码向HTML代码引入大量功能。这种类型的设计的好处是很明显的。同样,遵循角色分离、代码重用等也是非常有益的。您还将在小部件插件中看到这种类型的设计,因为它将简单的HTML代码转变成适用于插件的小部件。最重要的是,这也是您在这里需要完成的任务,即编写一个插件来将一个简单的表转变成排序和汇总表。
记住:尽量多使用jQuery代码进行设置,并且尽可能少使用HTML。