[英]Passing variables in nested functions between scripts
I am a newbie to jQuery and am trying to make a variable within a nested function available between scripts. 我是jQuery的新手,正在尝试在脚本之间的嵌套函数中创建变量。 However, I am unsure of how to do so (I am pretty bad at understanding scope).
但是,我不确定该怎么做(我很不了解范围)。 Here is the code (note: I copy-pasted this from jsFiddle, hence some tags are purposefully missing).
这是代码(请注意:我从jsFiddle复制粘贴了此代码,因此故意丢失了一些标签)。
<body>
<h1>Hello</h1>
<button id="btn">click</button>
<script>
var x;
$(document).ready(function() {
$(document).on("click", "#btn", function() {
x = "hello world";
});
});
</script>
<script>
alert(x);
</script>
</body>
Any help is appreciated! 任何帮助表示赞赏!
for that alert to alert Hello World
you need to add it inside the click function... since x is redeclare inside the click event . 对于提醒
Hello World
警报,您需要将其添加到click函数中...因为x在click事件中被重新声明。 and you don't have to seperate your <script>
. 而且您不必分隔
<script>
。
<script>
var x;
$(document).ready(function() {
$(document).on("click", "#btn", function() {
x = "hello world";
alert(x); //alerts hello world
});
alert(x); //alerts undefined since x is not set as this is executed before the click event as soon as document is ready
});
alert(x); //alerts undefined since x is not set
</script>
You are doing correctly, in your code <script> alert(x);</script>
when you are using alert x
value is not set. 您正在正确执行操作,未使用警报
x
未在代码<script> alert(x);</script>
设置。
HTML: HTML:
<button id="set">set</button>
<button id="get">get</button>
JS: JS:
var x;
$(document).ready(function () {
$(document).on("click", "#set", function () {
x = "hello world";
});
$(document).on("click", "#get", function () {
alert(x);
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.