Javascript 动态创建文件输入元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10644001/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Dynamically create file input element
提问by panda
I want to customize the file input button, so I use this code to create an file input element
我想自定义文件输入按钮,所以我用这段代码创建了一个文件输入元素
function inputBtn(){
var input=document.createElement('input');
input.type="file";
setTimeout(function(){
$(input).click();
},200);
}
<button id="ifile" onclick="inputBtn()">create</button>
However, when I click create, it shows nothing.
但是,当我单击创建时,它什么也没显示。
回答by Marc
You're creating the new DOM element, but you're not attaching it to the DOM. You need something like:
您正在创建新的 DOM 元素,但并未将其附加到 DOM。你需要这样的东西:
document.getElementById('target_div').appendChild(input);
You can see how this works in a poorly done JSFiddle here: http://jsfiddle.net/JQHPV/2/
你可以在这里看到它在一个做得不好的 JSFiddle 中是如何工作的:http: //jsfiddle.net/JQHPV/2/