AJax技术

译自Getting Started with jQuery(4)

字号+ 作者:H5之家 来源:H5之家 2015-10-15 11:13 我要评论( )

很多人试着控制所有的radio或者checkbox是否被选中,比如: $("input[type='checkbox']").each(function() {this.checked = true;// or, to uncheckthis.checked = false;// or, to togglethis.checked = !this.check

很多人试着控制所有的radio或者checkbox是否被选中,比如:

$("input[type='checkbox']").each(function() { this.checked = true; // or, to uncheck this.checked = false; // or, to toggle this.checked = !this.checked; });

注:在jQuery1.2及以上版本中,选择所有checkbox应该使用 input:checkbox , 因此以上代码第一行可写为:
$('input:checkbox').each(function() {

无论何时候,当你的代码出现each时,你应该重写上面的代码来构造一个插件,很直接地:

$.fn.check = function() { return this.each(function() { this.checked = true; }); };

这个插件现在可以这样用:

$('input:checkbox').check();

注:在jQuery1.2及以上版本中,选择所有checkbox应该使用 input:checkbox 原文为:$("input[type='checkbox']").check();

现在你应该还可以写出uncheck()和toggleCheck()了.但是先停一下,让我们的插件接收一些参数.

$.fn.check = function(mode) { var mode = mode || 'on'; // if mode is undefined, use 'on' as default return this.each(function() { switch(mode) { case 'on': this.checked = true; break; case 'off': this.checked = false; break; case 'toggle': this.checked = !this.checked; break; } }); };

这里我们设置了默认的参数,所以将"on"参数省略也是可以的,当然也可以加上"on","off", 或 "toggle",如:

$("input[type='checkbox']").check(); $("input[type='checkbox']").check('on'); $("input[type='checkbox']").check('off'); $("input[type='checkbox']").check('toggle');

如果有多于一个的参数设置会稍稍有点复杂,在使用时如果只想设置第二个参数,则要在第一个参数位置写入null.

从上一章的tablesorter插件用法我们可以看到,既可以省略所有参数来使用或者通过一个 key/value 对来重新设置每个参数.

作为一个练习,你可以试着将 的功能重写为一个插件.这个插件的骨架应该是像这样的:

$.fn.rateMe = function(options) { var container = this; // instead of selecting a static container with $("#rating"), we now use the jQuery context var settings = { url: "rate.php" // put more defaults here // remember to put a comma (",") after each pair, but not after the last one! }; if(options) { // check if options are present before extending the settings $.extend(settings, options); } // ... // rest of the code // ... return this; // if possible, return "this" to not break the chain });

Next steps(下一步)

如果你想做更好的javascript开发,建议你使用一个叫 FireBug的firefox插件. 它提供了断点调试(比alert强多了)、观察DOM变化等很多漂亮的功能

如果你还有未解决的问题,或者新的想法与建议,你可以使用jQuery的邮件列表 jQuery mailing list.

关于这个指南的任何事情,你可以写mail给作者或者发表评论在他的日志:blog.

关于这个指南的翻译任何事情,你可以写mail给我.或者在 BLOG中留言.

还有什么...

大大感谢John Resig创造了这么好的library! 感谢jQuery community 为John提供了如此多的咖啡和其他的一切!

© 2006, Jrn Zaefferer - last update: 2006-09-12 中文版翻译:Keel 上次更新:2006-12-13 -- 最后更新: 2009-3-10 访问本站首页

 

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

相关文章
网友点评