Javascript &引用;变量未定义";功能错误
我在函数中得到一个“变量未定义”错误。变量“recID”定义为:Javascript &引用;变量未定义";功能错误,javascript,Javascript,我在函数中得到一个“变量未定义”错误。变量“recID”定义为: var recID = 0; 我还有一个意见: <input type="text" id="rdy"> 然后我调用一个函数: <a href=""><input type="button" name="button" id="button" value="Next Hypothetical" onclick='reselectState()'></a> 功能是: <
var recID = 0;
我还有一个意见:
<input type="text" id="rdy">
然后我调用一个函数:
<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>
函数重新选择状态(){
var elem=document.getElementById(“rdy”);
元素值=累进;
var rdy=$(“#rdy”).val();
警报(rdy);
location.href='/impositional.cshtml?recordkey='+rdy;
}
我收到的错误显示“recID”未定义。这意味着
recID
不是全局变量。如果您发布更多的代码或完整的文件,这将非常有帮助。另一个问题可能是,recID
从未定义
在调用reselectState
之前,应该定义recID,如下所示:
var recID = 0;
function reselectState() {
var elem = document.getElementById("rdy");
elem.value = recID;
...
}
如果您使用以下任何一种方法定义它,recID
将不会是全局的:
(function(){
recID = 0;
});
anotherFunction = function(){
recID = 0;
}
如果这是问题所在,您可以使用窗口:
(function(){
window.recID = 0;
});
anotherFunction = function(){
window.recID = 0;
}
使用窗口或将其作为参数传递给函数。可能recID
超出范围。要检查是否发生了这种情况,请尝试window.recID
而不是var
您在哪里为recID赋值?您可能需要再次检查(链接已更新为更有用的资源)。如果希望其他函数可以访问您的recID
,请将其作为全局变量扫描在单个代码块中显示您的代码段。这样更容易找到确切的原因:-)因为我使用的是Microsoft Razor,所以需要将变量传递为“@recID”。代码正在运行。
(function(){
window.recID = 0;
});
anotherFunction = function(){
window.recID = 0;
}