我想我应该在这里发帖。我在jQuery上的第一个小时,实际上是有史以来第一次编程。我很想了解什么是不正确的,以及如何可以做得更好。
$(function() {
function hide_me()
//A place to specify which elements you want hidden, on page load.
{
$("li.credentials").hide();
}
function first_bow()
//The div right_column takes a bow on initial load.
{
$("div#right-column").show("drop");
}
function bigpeek()
//The third column toggles in/out. All elements under div right_column.
{
$("div#right-column").toggle("drop", "fast");
}
function smallpeek()
//Smaller snippets like credentials or user assignment flying in/out.
{
$("li.credentials").toggle("drop", "fast");
}
$(document).ready(function() {
$("*").ready(hide_me);
$("*").ready(first_bow);
$(".btn-new-email").click(bigpeek);
$(".button").click(smallpeek);
$(".icon-delete").mouseover(function() {
$(this).effect("bounce", "fast");
});
});
});
发布于 2011-03-29 10:27:24
关于编程,最好的学习方法是如何有效地重用代码。在您的代码中,您已经设置了一些函数,您自己声称这些函数将执行许多相同的操作。因此,您可以通过只编写代码来完成一次重复的任务,从而使它变得更好。
举个例子,我不会创建一个函数来放置一堆需要隐藏的东西,而是向应该隐藏的元素添加一个类,然后隐藏所有这些元素:
function hide_me()
//Hides anything with the "hide-me-onload" class
{
$(".hide-me-onload").hide();
}
发布于 2011-03-29 12:57:00
$(function () {
...
}
等同于
$(document).ready(function() {
...
}
因此,您可以将方法调用从$(.ready)函数()内部移动到$(function(){})内部。此外,尽可能使用ID而不是类名。下面这样的代码将遍历整个DOM来查找元素
$(".item")
更具体一点
$("#itemID") // use IDs instead of Classes
//If you have to use class name then you can speed up the selector by adding the element tag before it
$("div.item")
发布于 2011-03-29 13:05:04
在$(document).ready()
中使用$("*").ready()
是多余的...你已经知道使用所有的元素已经准备好了!而且,通常情况下,使用通用选择器$('*')
的效率非常低。
因此,您的$(document).ready()
的前两行可以是:
hide_me();
first_bow();
除此之外,还有一些关于组织和命名的问题,你有了一个很好的开始,保持下去!
https://stackoverflow.com/questions/5467181
复制相似问题