簡體   English   中英

使用JavaScript添加刪除HTML元素

[英]Add remove html element using javascript

我想創建一個表單以添加帶有標題的多個圖像。 由於我是php和mysql的人。 因此,如果我可以在單擊addmore時獲得新的字段,那么我可以做其余的php mysql部分。 如何設置var x來創建新行以提供新的瀏覽按鈕和標題文本字段。

<script type="text/javascript">
<!--
function addMore() {
if (document.getElementById && document.createElement) {
    var x = ;
    document.getElementById('inserthere').appendChild(x);
}
else alert('Your browser doesn\'t support the Level 1 DOM');
}

function delMore() {
if (document.getElementById && document.createElement) {
    var node = document.getElementById('inserthere')
    node.removeChild(node.childNodes[0]);
}
else alert('Your browser doesn\'t support the Level 1 DOM');
}
// -->
</script>

</head>

<body>
<table>
<tr><td>Select Image<input type="file" name="img[]" id="img"  /></td><td>Add caption
<input type="text" name="img_cap[]" id="img_cap" /></td>
</tr>
<span id="inserthere"></span>
</table>

<a href="javascript:addMore()" class="page">add More</a><br />
<a href="javascript:delMore()" class="page">remove</a>

</body>

直到有人回復我將要學習,探索互聯網並嘗試嘗試.....

這不是最漂亮的方法,但最簡單,最快的方法可能是為表提供id屬性(例如'imgtable' ),然后在addMore()函數中執行以下操作:

var x = document.createElement('tr'); // create a new row ready to add
x.innerHTML = '<td>Select Image<input type="file" name="img[]" id="img"  /></td><td>Add caption <input type="text" name="img_cap[]" id="img_cap" /></td>'; // fill it with your code
document.getElementById('imgtable').appendChild(x) // add the new row to the table

但是,如果您想了解更多信息,請務必先查找諸如document.createDocumentFragment()類的方法,以將單獨聲明的元素附加到對象上,然后再將其實際添加到DOM中。 我使用過的innerHTML方法可以更快,但是不那么整潔,並且比聲明文檔片段更難調試。

希望這可以幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM