2014年11月7日 17:10:40
之前寫過幾篇類似的文章,現在看來比較初級,弄一個高級的簡單的
情景: 后台要上傳游戲截圖,截圖數量不確定,因此使用動態添加input節點的方法去實現這個效果
主要用到的函數有:
document.getElementById();
objNode.parentNode;
objNode.cloneNode();
objNode.removeAtrribute();
objNode.innerHTML();
objNode.appendChild();
html:
1 <div class="well well-sm"> 2 <div class="form-group"> 3 <label class="form-label">游戲截圖:</label> 4 <input type="file" name="jietu[]" class="form-input"> 5 <span class="form-tip" onclick="add_jietu()"><font color="#428bca">點擊添加游戲截圖</font></span> 6 </div> 7 <div class="form-group" id="add_jietu"> 8 <label class="form-label">游戲截圖:</label> 9 <input type="file" name="jietu[]" class="form-input"> 10 </div> 11 </div>
javascript:
1 <script type="text/javascript"> 2 function add_jietu() 3 { 4 var add_jietu = document.getElementById('add_jietu'); 5 var nodeFather = add_jietu.parentNode; 6 var node_clone = add_jietu.cloneNode(); 7 content = add_jietu.innerHTML; 8 node_clone.removeAttribute('id'); 9 node_clone.innerHTML = content; 10 nodeFather.appendChild(node_clone); 11 } 12 </script>
注意:
1. js第6行使用的是"克隆節點"函數,克隆后的節點里邊並沒有html,需要第9行的代碼去填充內容
2. 使用克隆功能,因為該方法生成的變量類型是"節點類型", 才可以用到appendChild()函數里做參數
3. 節點的 nextSibling 和 lastChild 屬性得到的變量是 Text類型(在chrome的調試窗口中看到的)