在内部创建函数是否正确
$(document).ready(function() {
如下所示:
$(document).ready(function() {
function callMe() {
}
});
在DOM准备就绪并触发ready()
内的事件之前,不必调用.ready()
内的函数。
只是为了澄清一点--这是说明这个问题的代码:
$(function() {
var ind = 0;
// some event is executed and changes the value of the ind
// another event which affects the ind variable
// and another one - after this event we call our function
// there's another event - and we call our function again
我需要调用的函数需要ind
变量的更新值-我想我可以将其作为参数传递,但有没有更好的方法呢?
另外--另一件重要的事情是function()
也可以改变ind
变量的值--例如递增它(ind++
)。
发布于 2015-09-01 14:10:14
这也是可行的。
$(document).ready(function() {
callMe = function() {
alert('hello');
}
});
callMe();
如果您使用
var callMe = function () { ... }
它可能无法工作,并且您可能会收到错误消息"function is undefined“
发布于 2011-07-22 02:34:33
在$(document).ready
中创建函数时,可以保证在加载文档之前不会调用该函数。当然,它只能从该事件处理程序本身调用(稍后在事件处理程序中的某个位置)。
换句话说,你试图做的事情是有效的(尽管不一定是可取的--你必须透露更多关于你试图完成的事情)。
发布于 2015-05-01 00:00:56
你可以这样做:
$(document).ready(function(){
var callMe = function(){
//enter code here
}
$(".my-class").on("click", function(){
callMe();
});
});
因此,您不需要将函数放在文档之外,代码就会变得分组和更有条理。;)
https://stackoverflow.com/questions/6780890
复制相似问题