动态添加的元素不显示w / onChange

时间:2017-05-17 19:21:07

标签: javascript html input

我已经将这个JavaScript代码放在一个名为add()的函数中。

var newinput = document.createElement('div');
newinput.innerHTML = "<br><input type='file' id='" + counter + 
"'name='filename[" + counter + 
"]' accept='image/jpeg' onchange='add()'>";
document.getElementById('asd').appendChild(newinput);

但是我不想使用这个innerHTML来做这个新功能:

var newinput = document.createElement('input');
newinput.id=x;
newinput.type="file";
newinput.name="filename";
newinput.accept="image/jpeg";
newinput.onchange=add();

到目前为止,new函数创建了一个像innerHTML这样的输入,它是第一个函数之一,但是没有添加onchange属性(并且完全创建的输入甚至消失了,所以我必须评论{{ 1}};

有没有办法可以将“.onchange”添加到createElement var中,或者为.onchange()等几个输入创建一个JavaScript侦听器?
谢谢。

1 个答案:

答案 0 :(得分:2)

目前,您希望add()返回一个函数。不要调用该函数,只需执行:

newinput.onchange = add;

(function() {

  function add() {
    console.log("Added.");
  }

  function createFileInput(x) {
    var newinput = document.createElement('input');
    newinput.id = x;
    newinput.type = "file";
    newinput.name = "filename";
    newinput.accept = "image/jpeg";
    newinput.onchange = add;
    return newinput;
  }

  document.body.appendChild(createFileInput('my-input'));

})();

以下是您正在做的事情及其运作方式的示例:

(function() {

  function add() {
    return function() {
      console.log("Added.");
    }
  }

  function createFileInput(x) {
    var newinput = document.createElement('input');
    newinput.id = x;
    newinput.type = "file";
    newinput.name = "filename";
    newinput.accept = "image/jpeg";
    newinput.onchange = add();
    return newinput;
  }

  document.body.appendChild(createFileInput('my-input'));

})();

相关问题