【问题标题】:Cannot Read Property 'Elements' of Undefined - in JS Console无法读取未定义的属性“元素” - 在 JS 控制台中
【发布时间】:2013-10-25 22:18:58
【问题描述】:

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

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...");
} // }}}

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

Uncaught TypeError: Cannot read property 'elements' of undefined

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

【问题讨论】:

  • 您是从页脚运行函数SaveMotorSkills,还是在页面/html 出现在屏幕上之后?你应该是。
  • 它从一个单独的.js 文档运行,并且表单已经显示在屏幕上。当您单击表单底部的按钮时,它就会运行。

标签: javascript html ajax forms


【解决方案1】:

试试

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

另外,nested forms are not allowed,所以也需要解决。

【讨论】:

  • 这给了我新的错误:Uncaught TypeError: Cannot read property 'elements' of null
  • @KickingLettuce,SaveMotorSkills 什么时候运行?新的错误还在同一行,对吧?
  • 我在上面的 cmets 中添加了这个答案。
  • 您在 Chrome 中吗?试试这个:1)加载网页。 2) 按 F12 3) 单击控制台 4) 运行 document.getElementById('importSampleDataForm').elements.length;看看这会给你带来什么。
  • 你明白了。不允许嵌套表单,stackoverflow.com/questions/379610/can-you-nest-html-forms
猜你喜欢
  • 2018-11-10
  • 1970-01-01
  • 1970-01-01
  • 2017-09-09
  • 2013-02-02
  • 2015-11-14
  • 2020-06-04
  • 2016-01-12
  • 2021-04-29
相关资源
最近更新 更多