2016-03-08 86 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>