在jquery ready块内定义的函数与外部函数之间有什么区别? [英] what is the difference between a function defined inside jquery ready block and one outside

查看:161
本文介绍了在jquery ready块内定义的函数与外部函数之间有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用onclick属性向一个按钮注册一个函数,并在$()block中定义这个函数(我知道这是一个不好的习惯,这只是一个例子),当我点击按钮时,会发生一个错误: Uncaught ReferenceError:hello没有定义。这是我的代码:

I register a function to a button with onclick attribute, and define this function in $() block(I know it is a bad practice, and it is just an example), when I click the button, an error occurs: Uncaught ReferenceError: hello is not defined. Here is my code:

<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript">
$(function(){
    function hello(){
        alert('hello');
    }
});
</script>
</head>
<body>
<input type="button" id="btn" value="click" onclick="hello()"/>
</body>

如果我将hello函数代码放在$()块外面,它就可以工作。我知道$()是在解析DOM时执行的,当我点击按钮时,DOM必须已经被解析,那么为什么它会报错?
Thanks。

if I put hello function code out of $() block, it works. I know $() is executed when DOM is parsed, when I click the button, the DOM must already has been parsed, so why it reports an error? Thanks.

推荐答案

(没有定义)在 $。ready 块内保证在DOM准备好被访问/操作后执行。

There is no difference, except that functions executed (not defined) inside a $.ready block are guaranteed to execute after the DOM is ready to be accessed/manipulated.

你的问题是范围界定问题之一;你已经创建了一个局部函数,它在你的事件处理的全局范围内不可访问。

Your issue is one of scoping; you've created a local function which isn't accessable at the global scope where your event is being handled.

这篇关于在jquery ready块内定义的函数与外部函数之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆