javascript 无法读取未定义的属性“元素” - 在 JS 控制台中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19600288/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 16:08:02  来源:igfitidea点击:

Cannot Read Property 'Elements' of Undefined - in JS Console

javascripthtmlajaxforms

提问by TheLettuceMaster

HTML form (outputed thru PHP)

HTML 表单(通过 PHP 输出)

$retVal .= "<form id= 'importSampleDataForm' name = 'importSampleDataForm' onsubmit = \"return false\" >\n";

    // Form content edited out; it contains several dozen checkboxes

$retVal .= sprintf("<input type='button' class='wn_button' onclick='SaveMotorSkills();' value='Import Selected'>\n");
$retVal .= "</form>\n";

JavaScript / Ajax

JavaScript/Ajax

function SaveMotorSkills() // {{{
{
    // {{{ Ajax Header
    var httpRequest = CreateHttpRequest();
    if (!httpRequest) { 
        DialogFail('AJAX initialization error. ', 1 );
        return false; 
    } // }}}

    var params = '_SaveMotorSkills=1';
    for(i=0; i<document.importSampleDataForm.elements.length; i++) // line with error
    {
        params += "&" + document.importSampleDataForm.elements[i].name + 
            "=" + document.importSampleDataForm.elements[i].value ;
    }

    // edit out AJAX setup

    httpRequest.send(params);
    DialogSave("Saving...");
} // }}}

See "Line With Error Above" in forloop. JS Console says

请参阅for循环中的“上面有错误的行” 。JS 控制台说

Uncaught TypeError: Cannot read property 'elements' of undefined

Uncaught TypeError: Cannot read property 'elements' of undefined

I have looked at this code so much my eyes can't take it anymore. Does anyone else see anything I don't? I can add more code if needed.

我已经看了这么多代码,我的眼睛再也受不了了。有没有其他人看到我没有看到的东西?如果需要,我可以添加更多代码。

回答by Patrick

Try

尝试

document.getElementById('importSampleDataForm').elements.length

Also, nested forms are not allowed, so that also needs to be resolved.

此外,不允许嵌套表单,因此也需要解决。