在脚本之间传递嵌套函数中的变量

时间:2013-09-05 15:51:07

标签: jquery

我是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>

感谢任何帮助!

2 个答案:

答案 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);
    });
});

JSFiddle Demo