javascript函数在jquery $(document).ready块中不起作用 [英] javascript function does not work within jquery $(document).ready block
问题描述
我正在尝试从 onclick
触发器调用 JavaScript
函数。
I am trying to call a JavaScript
function from an onclick
trigger.
HTML
部分:
<div class="my_radio">
<input type="radio" name="my_radio" value="1" onclick="my_func()"/> first button
</div><!-- end of class my_radio -->
JavaScript
代码
<script type="text/javascript">
$(document).ready(function(){
function my_func(){
alert("this is an alert");
}
});
</script>
它不起作用。
但是如果我从 $(document).ready()
代码中保留 JavaScript
函数,它可以工作。以下是相关的代码段:
But if i keep the JavaScript
function out of the $(document).ready()
code, it works. Following is the relevant code snippet:
<script type="text/javascript">
$(document).ready(function(){
function my_func111(){
alert("this is an alert");
}
});
function my_func(){
alert("this is an alert");
}
</script>
1)为什么不是第一个 JavaScript
代码片段工作?
1) Why does not the first JavaScript
code snippet work?
2)如何让第一个 JavaScript
代码片段正常工作?
2) How can I get the first JavaScript
code snippet working ?
编辑:
如我所知, $(文件)网页完全加载时执行.ready()
。那么如果我写 my_func()
my_func()在完成页面加载之前或之后处于活动状态>外 $(文件).ready()
?
SO FAR AS I KNOW, $(document).ready()
is executed when the web page loads completely. So how can I prevent my_func()
to be active before or after the complete page-loading if I write my_func()
outside $(document).ready()
?
推荐答案
这都是关于javascript执行上下文和范围的。
It's all about javascript execution contexts and scope.
一切您在函数中定义的仅在此函数中知道。
Everything that you define within a function is know only in this function.
在第一次测试中,函数 my_func()
只能在ready回调内(以及内部其他对象中)使用。你不能在外面引用它。
In your first test, the function my_func()
can only be used within the ready callback (and in the inner other objects). You can't reference it outside.
在你的第二个例子中,函数 my_func()
是全局的文档,可以从任何地方访问。
In your second example, the function my_func()
is global to the document and accessible from anywhere.
我认识到这可能是一个简单的简单解释: - )
I recognize this is maybe a verry simple explanation :-)
这篇关于javascript函数在jquery $(document).ready块中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!