Jquery:从不同文档调用函数
我将一些 Jquery 函数保存在“custom.js”文件中。在某些页面上,我需要将 PHP 变量传递给 Jquery,因此一些 Jquery 位需要保留在 HTML 文档中。然而,当我现在尝试将事情重构到最低限度时,我遇到了以下问题:
如果我将其放入我的 custom.js 中:
$(document).ready(function()
{
function sayHello() {
alert("hello");
}
}
并且将其放入 HTML 文档中:
<script type="text/javascript">
$(document).ready(function()
{
sayHello();
});
</script>
... 该函数不会被调用。然而,如果两者都放在 HTML 文档中,该函数就可以正常工作。
我是否需要为该函数声明某种公共属性,或者如何在 HTML 中获取 Jquery 函数以与外部 .js 文件对话?它们被正确包含并且在其他方面工作正常。
谢谢。
I've got some Jquery functions that I keep in a "custom.js" file. On some pages, I need to pass PHP variables to the Jquery so some Jquery bits need to remain in the HTML documents. However, as I'm now trying to refactor things to the minimum, I'm tripping over the following:
If I put this in my custom.js:
$(document).ready(function()
{
function sayHello() {
alert("hello");
}
}
And this in a HTML document:
<script type="text/javascript">
$(document).ready(function()
{
sayHello();
});
</script>
... the function doesn't get called. However, if both are placed in the HTML document, the function works fine.
Is there some kind of public property I need to declare for the function or how do I get Jquery functions in my HTML to talk to external .js files? They're correctly included and work fine otherwise.
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
问题是您在这一行声明的匿名函数中定义了 sayHello :
因此,sayHello 的作用域仅限于该函数。如果您希望从应用程序中的其他任何位置(例如页面上的 HTML 或 custom.js 中的另一行)调用
sayHello
,则需要更改 custom.js 并将其定义在调用之外$(文档).ready
:The problem is you're defining
sayHello
within the anonymous function that is declared on this line:As a result,
sayHello
is scoped to only that function. If you wish to callsayHello
from anywhere else in your application, such as the HTML on your page or another line in custom.js, you will need to change custom.js and define it outside the call to$(document).ready
:只需将函数设置为全局变量即可
just make the function a global variable