我是jQuery的新手,我试图在脚本之间的嵌套函数中创建一个变量。但是,我不确定如何这样做(我很难理解范围)。这是代码(注意:我从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>
感谢任何帮助!
答案 0 :(得分:1)
警告Hello World
的警报需要在点击功能中添加...
因为x是click事件中的重新声明。而且您不必分开<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>
答案 1 :(得分:1)
当您使用提醒<script> alert(x);</script>
时,您的代码x
中的代码正确无法设置。
HTML:
<button id="set">set</button>
<button id="get">get</button>
JS:
var x;
$(document).ready(function () {
$(document).on("click", "#set", function () {
x = "hello world";
});
$(document).on("click", "#get", function () {
alert(x);
});
});