jquery – $(document).ready函数内的函数
在其中创建函数是否正确
$(document).ready(function() {
像这样:
$(document).ready(function() { function callMe() { } });
.ready()
内部的函数不必在dom准备好之前调用,并且触发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++
)。
是的,你可以这样做,这只是一个范围问题; 如果你只需要从$(document).ready(function() { })
访问callMe()
,那么可以将函数放在那里,并提供一些架构优势,因为你无法访问该函数之外的函数上下文。 如果您需要在文档就绪之外使用callMe()函数,则需要在该上下文之外定义callMe()函数。
function callMe() { // Do Something } $(document).ready(function() { callMe(); });
UPDATE
根据您的澄清,您有两种选择:
1)在ready()之外的DECLARE变量,但是然后在ready()中定义变量
var someVariable; function callMe() { someVariable++; alert(someVariable); } $(document).ready(function() { someVariable = 3; callMe(); // Should display '4' });
2)在准备好之内,使用window.yourVariable = 'whatever';
定义变量window.yourVariable = 'whatever';
这也有效。
$(document).ready(function() { callMe = function() { alert('hello'); } }); callMe();
如果你使用
var callMe = function () { ... }
它可能无法正常工作,您可能会收到错误“函数未定义”
在$(document).ready
创建函数时,可以保证在文档加载之前不会调用它。 当然,它只能从事件处理程序本身调用(稍后在事件处理程序中的某个地方)。
换句话说,你要做的事情是有效的(虽然不一定是可取的 – 你必须透露更多关于你想要完成的事情)。
你可以这样做:
$(document).ready(function(){ var callMe = function(){ //enter code here } $(".my-class").on("click", function(){ callMe(); }); });
因此,您不需要将函数放在文档之外,代码就会变得分组并且更有条理。 ;)
直接调用函数可能是一个更好的主意:
$(document).ready(myFunction); function myFunction() { // Your code here }
这绝对是合法的。 问题是你为什么要这样做? 可能将函数的范围绑定到ready的范围,而不是将其全局绑定到window对象。 但那是你真正想要的吗? 我建议看一下javascript中的函数闭包以及它如何处理作用域。 帮助澄清它的必要性……
通过将标记移动到html文件的底部,查看是否可以消除使用document.ready的需要。 这应该会使事情变得更简单。 否则,将该函数声明在document.ready范围之外,并在document.ready函数范围内调用它。