1

我有这个 javascript。我的表单中肯定有 2 个名为“附件”的输入标签:

<input name="attachments" type="hidden" value="test.doc">
<input name="attachments" type="hidden" value="test2.doc">

这是我的javascript。它说我的浏览器中未定义变量附件:

var attachments = document.getElementsByName('attachments');

var picCnt = 0;
var resumeCnt = 0;

if(document.getElementsByName('attachments').length >0){
    for(var i = 0; i <= attachments.length; i++){
        if(attachments[i].value.substring(attachments[i].value.length-4, attachments[i].value.length) == ".doc" ||
        attachments[i].value.substring(attachments[i].value.length-5, attachments[i].value.length) == ".docx" ||
        attachments[i].value.substring(attachments[i].value.length-4, attachments[i].value.length) == ".pdf" ){
            resumeCnt += 1;
        }
    }
}

这是不正确的吗?蒂亚!

4

1 回答 1

3

以下行是undefined问题:

for(var i = 0; i <= attachments.length; i++){

它应该是:

for(var i = 0; i < attachments.length; i++){

最有可能的报告attachments[attachments.length]undefined,因为它总是如此。

只是一个建议

我发现上面的内容很难阅读,使用单个变量比每次重复相同的数组访问要好得多。

var attachments = document.getElementsByName('attachments'),
    picCnt = 0;
    resumeCnt = 0;
    i, val
;

if(attachments.length >0){
    for(i = 0; i <= attachments.length; i++){
        val = attachments[i].value;
        if(val.substring(val.length-4, val.length) == ".doc" || 
           val.substring(val.length-5, val.length) == ".docx" ||
           val.substring(val.length-4, val.length) == ".pdf" ){
        resumeCnt += 1;
    }
}

}

于 2013-01-11T17:49:57.883 回答