繁体   English   中英

函数中的“变量未定义”错误

[英]“Variable is undefined” error in function

我在函数中收到“变量未定义”错误。 变量“ recID”定义为:

var recID = 0;

我也有一个输入:

<input type="text" id="rdy">

我为变量分配了一个值(对于这个问题,这是实际分配值的修改版本):

recID = 3;

然后我调用一个函数:

<a href=""><input type="button" name="button" id="button" value="Next Hypothetical" onclick='reselectState()'></a>

该函数是:

<script>
    function reselectState() {
        var elem = document.getElementById("rdy");
        elem.value = recID;

        var rdy = $("#rdy").val();
        alert(rdy);
        location.href = '/hypothetical.cshtml?recordkey=' + rdy;
    }
    </script>

我收到的错误消息说“ recID”是不确定的。

这意味着recID不是全局变量。 如果您发布更多代码或完整文件,这将真的有帮助。 另一个问题可能是从未定义recID

你应该定义recID之前reselectState被称为像这样:

var recID = 0;

function reselectState() {
    var elem = document.getElementById("rdy");
    elem.value = recID;

    ...
}

如果使用以下任何方法定义它,则recID将不是全局的:

(function(){
  recID = 0;
});

anotherFunction = function(){
  recID = 0;
}

如果这是问题,您可以使用window来解决:

(function(){
  window.recID = 0;
});

anotherFunction = function(){
  window.recID = 0;
}

使用窗口或将其作为参数传递给函数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM