javascript 无法将onkeydown属性添加到动态创建的输入

5ssjco0h  于 2023-04-28  发布在  Java
关注(0)|答案(2)|浏览(99)

HTML:

<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>

changeIt函数:

<script>
let div = document.getElementById("df2");
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(event)';
    newInput.class = 'form-control';
    inputs.appendChild(newInput);
    console.log(newInput);
  }
}
</script>

控制台只显示新输入的type & name属性。这使得新的输入不能再次产生新的输入(它停止产生仅创建2个输入,原始和新的)。如何解决这个问题?

wnavrhmk

wnavrhmk1#

当通过Javascript创建时,事件侦听器必须是函数,而不是字符串。使用

// Good.
newInput.onkeydown = changeIt;

// Good.
newInput.onkeydown = event => changeIt(event);

// Good.
newInput.addEventListener('keydown', changeIt);

而不是

// Bad.
newInput.onkeydown = "changeIt(event)";
z5btuh9x

z5btuh9x2#

这是零钱

let div = document.getElementById("df2");
    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[]';
            //look here   
            newInput.addEventListener('keydown',changeIt);
             newInput.classList = 'form-control';
            inputs.appendChild(newInput);
        }
    }

相关问题