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

如何使用JavaScript将input的type从text改为date?

解决方案

你之前的代码没生效是因为选错了目标元素:question_count是显示"2."的span标签的类,而你要修改的是带有sq_field类的input标签,操作对象完全不对,所以自然改不了type属性。

以下是几种可行的实现方式:

方法1:通过类名获取元素(getElementsByClassName)

getElementsByClassName会返回所有带指定类名的元素集合,取第一个元素修改type即可:

document.getElementsByClassName('sq_field')[0].type = 'date';

方法2:使用querySelector(更简洁)

querySelector可以直接通过CSS选择器定位元素,写法更灵活:

// 直接通过类名选中目标input
document.querySelector('.sq_field').type = 'date';

// 或者更精准,明确指定是input标签(避免其他带sq_field类的元素干扰)
document.querySelector('input.sq_field').type = 'date';

注意事项

如果页面元素是动态加载的(比如通过AJAX渲染),要确保代码在元素加载完成后执行,可以把代码放在DOMContentLoaded事件监听里:

document.addEventListener('DOMContentLoaded', function() {
  document.querySelector('input.sq_field').type = 'date';
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 07:32:40