如果我在启动时有很多函数,它们是不是都必须放在一个下面:
$(document).ready(function() {或者我可以有多个这样的语句?
发布于 2009-08-25 11:47:23
您可以有多个,但这并不总是最好的做法。尽量不要过度使用它们,因为这会严重影响可读性。除此之外,这是完全合法的。请参阅以下内容:
http://www.learningjquery.com/2006/09/multiple-document-ready
试试这个:
$(document).ready(function() {
alert('Hello Tom!');
});
$(document).ready(function() {
alert('Hello Jeff!');
});
$(document).ready(function() {
alert('Hello Dexter!');
});你会发现它等同于这个,注意执行的顺序:
$(document).ready(function() {
alert('Hello Tom!');
alert('Hello Jeff!');
alert('Hello Dexter!');
});同样值得注意的是,定义在一个$(document).ready块中的函数不能从另一个$(document).ready块调用,我只是运行了这个测试:
$(document).ready(function() {
alert('hello1');
function saySomething() {
alert('something');
}
saySomething();
});
$(document).ready(function() {
alert('hello2');
saySomething();
}); 输出为:
hello1
something
hello2发布于 2009-08-25 11:49:55
您可以使用多个。但您也可以在一个document.ready中使用多个函数:
$(document).ready(function() {
// Jquery
$('.hide').hide();
$('.test').each(function() {
$(this).fadeIn();
});
// Reqular JS
function test(word) {
alert(word);
}
test('hello!');
});发布于 2009-08-25 11:47:55
是的,你可以很容易地拥有多个块。只是要注意它们之间的依赖关系,因为评估顺序可能不是您所期望的。
https://stackoverflow.com/questions/1327756
复制相似问题