[英]For loop returns undefined variable
var formobj = document.h1;
for (var j = 0; j < formobj.elements.length; j++) {
if (formobj.elements[j].type == "radiobutton" && formobj.elements[j].checked) {
var wholebase = formobj.elements[j].value;
}
}
Later in the script, the variable is set to the inner html of a div and is labeled as undefined.在脚本的后面,变量被设置为 div 的内部 html 并标记为未定义。 Is there a flaw in my for loop?我的for循环有缺陷吗?
There is no type radiobutton
, I think you want type == 'radio'
.没有 type radiobutton
,我想你想要type == 'radio'
。
Your wholesale
variable is defined within the inner scope. Once you leave this scope the variable no longer exists.您的wholesale
变量在内部 scope 中定义。一旦您离开此 scope,该变量将不再存在。 Read about Javascript scope here or here . 在此处或此处阅读有关 Javascript scope 的信息。 You can change your code like this:您可以像这样更改代码:
var wholebase = null; //<-- declare the variable here
var formobj = document.h1;
for (var j = 0; j < formobj.elements.length; j++){
if (formobj.elements[j].type == "radiobutton" && formobj.elements[j].checked){
wholebase = formobj.elements[j].value;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.