有没有人对整理以下代码有建议:
/* Example code only to demonstrate the type of code my app contains and
will contain more of */
$("#filter").click(function()
{
if($(this).attr("value") != "" && $(this).attr("value").length > charLimit)
filterable($(this).attr("value"))
});
$("#filter").keyup(function()
{
if($(this).attr("value") == "" || $(this).attr("value").length <= charLimit)
{
$('.alphablock').show(300);
$('.filterable a').removeClass("selected");
}
});
$('.slidingForm fieldset').hide();
$('.slidingForm fieldset:first').find(':input:first').focus();
/* Snip More Code */
基本上,我最终为我的每个元素编写了很多代码,这只是一堆东西,虽然可行,但它只会变得更大,更难维护和开发。
我非常了解 PHP,我通常会求助于类来将代码保存在可维护的 block 中。但我不确定 jQuery 和一般 javascript 功能的最佳方法,它们的使用方式完全不同,因为它的过程较少,并且可以根据用户交互随时调用函数。
谢谢 jack
最佳答案
这一切都非常干净,但有一些我最近一直在做的事情我会推荐:
(function($)
{
"use strict";
// Variables declared here are scoped to this function, won't polute
// the globals.
$(function()
{
// Do your work here.
});
})(jQuery);
将您的脚本包含在函数本身内,允许您声明不会全局创建的变量。如果你需要做一些全局的东西,把它分配给 window
对象:
window.something = {};
我还会考虑将您的 jquery 对象分配给一个变量,重复选择相同的对象是没有意义的,例如$("#filter")
、$(this)
等
最后一件事是如果您使用类选择器,则更喜欢在标签名称前加上前缀,例如$("div.slidingForm")
而不是 $(".slidingForm")
。虽然您可能不会注意到简单页面上的任何差异,但在您进行大量选择的更复杂页面上,最好允许浏览器使用 native getElementsByTagName
方法提取元素的子集来匹配类选择器,而不必遍历整个 DOM。
关于javascript - 如何编写并保持简洁、易于理解的 Javascript 和 jQuery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8731397/