我已经在名为 add()
的函数中包含了这段 JavaScript 代码。
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();
到目前为止,新函数创建了一个类似于第一个函数的innerHTML的输入,但没有添加onchange
属性(并且完整创建的输入甚至消失了,所以我必须评论.onchange()
;
有没有办法可以将“.onchange”添加到 createElement var 或为诸如 input.onchange() = function (){}
之类的几个输入创建 JavaScript 监听器?
谢谢。
最佳答案
就目前而言,您期望 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'));
})();
关于javascript - 动态添加的元素不显示 w/onChange,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44033157/