Node.appendChild: 参数1没有在纯JS中实现接口Node

Node.appendChild: Argument 1 does not implement interface Node in pure JS

我正在尝试创建一个带有列表的表单。该按钮负责将新元素添加到表单中的列表中。 HTML:

<form id="newBrand">
        <fieldset>
            <ul id="formCars">
              <li>
                <legend>Car 1</legend>
                <label>Name
                    <input type="text" name="carName1" />
                </label>
              </li>
            </ul>
        </fieldset>
        <button type="button" id="addCar">+</button>
</form>

还有我的JS代码:

        const form = document.getElementById('newBrand');
        const formCars = document.getElementById('formCars');  
        const addCarBtn = document.getElementById('addCar');
        addCarBtn.addEventListener('click', () => formCars.appendChild(createBrandCar));

        function createBrandCar() {
            const result = document.createElement('li');
            let size = formCars.getElementsByTagName('li').length;
            result.innerHTML = `
                <legend>Car ${size}</legend>
                <label>Name
                    <input type="text" name="carName${size}" />
                </label>`;
            return result
        }

我的应用程序呈现正常,但是当我单击按钮时出现此错误:

Uncaught TypeError: Node.appendChild: Argument 1 does not implement interface Node.

此错误指向包含此代码的行:

addCarBtn.addEventListener('click', () => formCars.appendChild(createBrandCar));

我该怎么做才能防止发生此错误?

您应该通过在函数名称后指定括号来调用该函数:

addCarBtn.addEventListener('click', () => formCars.appendChild(createBrandCar()));

此外,由于您在页面加载时已经有一个列表项,因此您应该将大小增加 1:

let size = ++formCars.getElementsByTagName('li').length;

演示:

const form = document.getElementById('newBrand');
const formCars = document.getElementById('formCars');  
const addCarBtn = document.getElementById('addCar');
addCarBtn.addEventListener('click', () => formCars.appendChild(createBrandCar()));

function createBrandCar() {
    const result = document.createElement('li');
    let size = ++formCars.getElementsByTagName('li').length;
    result.innerHTML = `
        <legend>Car ${size}</legend>
        <label>Name
            <input type="text" name="carName${size}" />
        </label>`;
    return result
}
<form id="newBrand">
    <fieldset>
        <ul id="formCars">
          <li>
            <legend>Car 1</legend>
            <label>Name
                <input type="text" name="carName1" />
            </label>
          </li>
        </ul>
    </fieldset>
    <button type="button" id="addCar">+</button>
</form>