You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何获取图书馆应用表单中三个输入框的值?

获取表单输入值并存储到数组的解决方案

你当前用firstChild.firstChild定位输入框的方式不可靠,因为HTML里的换行、空格会被解析成空白文本节点,导致你拿到的不是目标输入元素。下面给你几种健壮的实现方式:

方法1:通过ID直接获取(最直观)

每个输入框都有唯一ID,直接用getElementById定位最稳妥:

// 先获取表单和按钮元素
const newForm = document.getElementById('new-book-form');
const submitBtn = document.getElementById('create-book');

submitBtn.addEventListener('click', (event) => {
    event.preventDefault();
    
    // 获取三个输入框的值
    const title = document.getElementById('title').value;
    const author = document.getElementById('author').value;
    const pages = document.getElementById('pages').value;
    
    // 存入数组
    const book = [title, author, pages];
    console.log(book); // 可以打印验证结果
});

方法2:利用表单的elements属性(更精准)

直接通过表单对象的elements属性,按输入框的name值获取,避免全局DOM查找:

const newForm = document.getElementById('new-book-form');

// 监听表单submit事件(比按钮click更全面,支持回车提交)
newForm.addEventListener('submit', (event) => {
    event.preventDefault();
    
    const title = newForm.elements.title.value;
    const author = newForm.elements.author.value;
    const pages = newForm.elements.pages.value;
    
    const book = [title, author, pages];
    console.log(book);
});

方法3:用querySelector定位(灵活)

如果习惯用CSS选择器,也可以用querySelector:

const submitBtn = document.getElementById('create-book');

submitBtn.addEventListener('click', (event) => {
    event.preventDefault();
    
    const title = document.querySelector('#title').value;
    const author = document.querySelector('#author').value;
    const pages = document.querySelector('#pages').value;
    
    const book = [title, author, pages];
    console.log(book);
});

额外提示

  • pages输入框是number类型,但获取到的value是字符串,要是需要数字类型,可以用Number(pages)转换
  • 尽量避免依赖DOM节点的位置(比如firstChild),一旦HTML结构调整(比如加个换行、嵌套元素),代码就会失效,用ID、name或选择器的方式更健壮

内容的提问来源于stack exchange,提问作者Monnt

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 05:52:41