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

动态创建input无法添加onkeydown属性,无法连续生成输入框怎么办?

问题解决:动态生成输入框无法触发onkeydown事件

你的代码存在两个关键问题,导致新输入框无法触发事件,且控制台看不到类名属性:

错误点1:事件绑定方式错误

创建新输入框时,你用了字符串赋值newInput.onkeydown = 'changeIt(event)',这种写法只适用于HTML标签内的事件属性,在JS中直接操作DOM元素时,需要直接赋值函数引用,而不是字符串。

错误点2:类名属性设置错误

JS中操作DOM元素的类名时,不能直接用class(它是JS的保留字),必须用className属性,这就是控制台看不到form-control类的原因。

修正后的完整代码

<form id="form">
  <div class="form-group" id="df2">
     <input type="text" class="form-control" name="atribut[]" onkeydown="changeIt(event)">
  </div>
  <div class="form-group" id="inputs">
  </div>
</form>

<script>
let inputs = document.getElementById("inputs");
function changeIt(event) {
  var key = event.which || event.keyCode;
  if (key === 13) {
    const newInput = document.createElement('input');
    newInput.type = 'text';
    newInput.name = 'atribut[]';
    // 正确绑定事件:直接赋值函数引用
    newInput.onkeydown = changeIt;
    // 正确设置类名
    newInput.className = 'form-control';
    inputs.appendChild(newInput);
    // 自动聚焦新输入框,提升操作体验
    newInput.focus();
    console.log(newInput);
  }
}
</script>

额外优化:判断按键时用数字13比字符串'13'更严谨,避免类型转换问题;新增newInput.focus()让新输入框自动获得焦点,无需手动点击。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 02:22:26