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

如何从文本字段获取值?获取class为control term的input值返回undefined

解决获取文本框内容返回undefined的问题

嘿,我懂你卡在这里的困惑!你遇到的问题其实很常见——你选中的元素不对。

你写的代码document.getElementsByClassName("control term")[0].value,这里getElementsByClassName("control term")获取到的是那个带class="control term"的<div>元素,而div本身是没有.value属性的,所以自然返回undefined。真正存储着"cpsc"值的是div里面的<input>标签哦!

给你几个可行的解决方案:

  • 先获取目标div,再定位里面的input元素:
    document.getElementsByClassName("control term")[0].querySelector('input').value
    
  • 更简洁的方式:直接用复合选择器定位input,推荐用querySelector(比getElementsByClassName更灵活):
    document.querySelector('.control.term input').value
    
  • 如果input有其他唯一标识(比如name属性),也可以直接定位:
    // 假设input有name="course"
    document.querySelector('input[name="course"]').value
    

你可以先在控制台打印document.getElementsByClassName("control term")[0],看看输出的是不是那个div元素,就能直观理解问题所在啦~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 10:14:22