【问题标题】:How to set and get the value of a global variable ? [duplicate]如何设置和获取全局变量的值? [复制]
【发布时间】:2015-01-18 17:42:16
【问题描述】:

我正在尝试设置和获取全局变量的值。这是jsfiddle

HTML

<input type="button" value="setValue" onClick="setValue()">
<input type="button" value="getValue" onClick="getValue()">

JS

//setting global variable
var theValues = '';

function setValue() {
    theValues = "test";
    alert(theValues);
}

function getValue() {
    alert(theValues);
}

但它不会抛出错误并且不工作

【问题讨论】:

  • 什么错误?调用全局变量时尝试 window.theValue

标签: javascript


【解决方案1】:

您必须更改 jsFiddle 设置以允许您的代码真正位于全局命名空间中。现在,您的代码在 onload 处理程序中,因此不是全局的,因此在您的 HTML 中指定的事件处理程序找不到,因此永远不会调用。

在 jsFiddle 的左上角,将显示 "onLoad" 的下拉菜单更改为 "No wrap - in head"。然后,您的 jsFiddle 将像这里一样工作:http://jsfiddle.net/r8fsh3ek/2/

【讨论】:

    【解决方案2】:

    你也可以这样做

    <input type="button" value="setValue" onClick="setValue()">
    <input type="button" value="getValue" onClick="getValue()">
    

    您的 javascript 代码:-

    var theValue= '';
     function setValue() {
       theValues = "test";
        alert(theValues);
         return theValues;
    }
    
    function getValue() {
        theValues = setValue();
        alert(theValues);
      }
    

    【讨论】:

    • 你做了什么改变,为什么?为什么返回值会使setValue 工作?在getValue 内部调用setValue 似乎没有多大意义。
    • 我刚刚给出了另一种设置变量的方法。
    • 还有什么办法?
    • 我在上面的代码中改变的东西。
    • return theValues;如何设置变量?无论哪种方式,如果您阅读接受的答案,您将看到实际问题是什么。 OP 设置变量的方式没有任何问题。
    猜你喜欢
    • 1970-01-01
    • 2012-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多