【问题标题】:Uncaught TypeError when calling function from button从按钮调用函数时未捕获的 TypeError
【发布时间】:2020-06-26 09:23:00
【问题描述】:

我正在制作一个表格来记录一群人的数据,当按下按钮添加另一个人时,控制台会吐出一个 TypeError,说 addPerson() 不是一个函数。

HTML(正文):

<form method="POST">
    <h3> People </h3>
    <div class="person">
        <p>
            <label>Name</label>
            <input type="text" name="name" />
            <br/>
        </p>
        <p>
            <label>Gender</label>
            <input type="radio" name="gender" value="male" />Male
            <input type="radio" name="gender" value="female" />Female
            <br />
        </p>
        <p>
            <label>Date of Birth</label>
            <input type="date" name="dob" />
            <br/>
        </p>
    </div>
    <br/>
    <input type="button" value="Add another person" onclick="addPerson()" id="addPerson" />
</form>
<script src="client.js"></script>

Javascript:

function addPerson(){
    let personForm = document.getElementsByClassName("person")[0];
    let personFormCopy = personForm.cloneNode(true);
    let buttonNode = document.getElementById("addPerson");
    document.body.insertBefore(personFormCopy, buttonNode);

    let br150 = document.createElement("br");
    document.body.insertBefore(br150, buttonNode);

    br150.style.lineHeight="150px";
}

错误:

Uncaught TypeError: addPerson is not a function at HTMLInputElement.onclick

【问题讨论】:

    标签: javascript html forms button typeerror


    【解决方案1】:

    您的函数名称和按钮 ID 相同。自从 IE 引入了这种行为,一些浏览器 add DOM element IDs to the window scope,这导致你的情况发生冲突。

    这个问题可以通过将按钮的ID更改为addPersonBtn等解决。

    但是,我建议不要混合使用 HTML 和 JS。您可以改为删除 HTML 中的 onclick 属性,然后像这样编写您的 JS:

    document.getElementById('addPersonBtn').addEventListener('click', addPerson);
    
    function addPerson(){
        console.log('It worked.');
    }
    &lt;button id="addPersonBtn"&gt;Click me&lt;/button&gt;

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多