【问题标题】:Javascript Textbox value returning object errorJavascript文本框值返回对象错误
【发布时间】:2013-07-09 14:55:01
【问题描述】:

我一直在使用一个简单的表格来计算某人下订单的总金额。我为表单使用了一个预设框架,它使用输入文本来确定项目的数量。

由于某种原因,当我访问该值,将其转换为字符串,然后调用它的长度时,我收到错误“SCRIPT438:对象不支持属性或方法'长度'”。当我对值的类型执行 console.log() 时,我确实得到了一个字符串。

为什么我会收到这个错误?

如果不清楚,我只是在寻找解决此错误的方法,而不是代码批评。

控制台文本: LOG:a,小:2 日志:文本值:2 LOG:文本类型Val:字符串 SCRIPT438:对象不支持属性或方法“长度” 130号线

function numOnly(a){//used to check that only a number has been inputted into the quantity box
var textVal = document.getElementById(a).value.toString();
console.log("textVal: "+textVal);
console.log("type of textVal: "+typeof textVal);
var returnVal = '';
for(var i = 0;i<textVal.length();i++){
    if(textVal.charAt(i)=='0'||textVal.charAt(i)=='1'||textVal.charAt(i)=='2'||textVal.charAt(i)=='3'||textVal.charAt(i)=='4'||textVal.charAt(i)=='5'||textVal.charAt(i)=='6'||textVal.charAt(i)=='7'||textVal.charAt(i)=='8'||textVal.charAt(i)=='9'){
        returnVal+=textVal.charAt(i);
    }//if
}//for
console.log("a after loop: "+a);
return returnVal;
function numOnly(a){//used to check that only a number has been inputted into the quantity box WHY DOES IT GET AN OBJECT WINDOW
var textVal = '';
textVal = document.getElementById(a).value.toString();
console.log("textVal: "+textVal);
console.log("type of textVal: "+typeof textVal);
var returnVal = '';
for(var i = 0;i<textVal.length();i++){
    if(textVal.charAt(i)=='0'||textVal.charAt(i)=='1'||textVal.charAt(i)=='2'||textVal.charAt(i)=='3'||textVal.charAt(i)=='4'||textVal.charAt(i)=='5'||textVal.charAt(i)=='6'||textVal.charAt(i)=='7'||textVal.charAt(i)=='8'||textVal.charAt(i)=='9'){
        returnVal+=textVal.charAt(i);
    }//if
}//for
console.log("a after loop: "+a);
return returnVal;
}//numOnly()

我在哪里调用函数

case "S":
a=document.getElementById(sizeId[i]);
console.log("a, small: "+a.value);
if(a!=null) SSTotal+=(parseInt(numOnly(sizeId[i]))*prices[1]);
break;

【问题讨论】:

  • length 是属性而不是方法,来自 html 元素的值已经是字符串,因此 toString 是无用的,您可以使用括号表示法代替 charAt ... textVal[i] === "0"

标签: javascript string object textbox


【解决方案1】:

长度是一个属性而不是一个方法,所以试试吧:

textVal.length

而不是

textVal.length()

您也不需要对值执行toString()。它本身就是字符串。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-15
    • 2013-02-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多