2016-03-08 87 views
1

当我使用js单击按钮时,我想插入一个输入(type = file),但输入元素出现的时间为毫秒,然后消失。 这里是我的代码:动态创建输入

function addInputImg(){ 
      var div2 = document.getElementById("imgFiles"); 
      var inputImg = document.createElement('input'); 
      inputImg.type = 'file'; 
      div2.appendChild(inputImg);  
     } 
<form ...> 
. 
. 
<button id='btnAgregarImg' onclick="addInputImg();">Agregar imagen</button> 
<div id='imgFiles'> 
</div> 
</form> 

回答

0

将按钮类型更改为“按钮”以防止提交表单。

https://jsfiddle.net/g5Lxr2ac/

<button id='btnAgregarImg' type="button" onclick="addInputImg();">Agregar imagen</button> 
2

按钮<button>一个form元素中被当作默认情况下,submit按钮。在你的情况下,当你按下表单中的按钮时,表单将被提交,页面每次获得reloaded

尝试将您的按钮的类型attribute设置为button以避免此问题。

<button type="button" id='btnAgregarImg' onclick="addInputImg();">Agregar imagen</button> 
0

更改此:

<button id='btnAgregarImg' onclick="addInputImg();">Agregar imagen</button> 

要这样:

<button id='btnAgregarImg' type="button" onclick="addInputImg();">Agregar imagen</button>