【发布时间】:2021-04-06 14:19:08
【问题描述】:
所以我的页面中已经有了这些元素:
<button id="addMore" class="button" style="background-color: green;">+</button>
<button id="removeMore" class="button" style="background-color: red;">-</button>
<div id="fieldList">
<select style="width:100%" id="prisplan" name="prisplan[]" required>
<option selected value="">Velg prisplan</option>
<?php foreach($eachlines as $lines){ //add php code here
echo "<option value='".$lines."'>$lines</option>";
}?>
</select>
<input type="text" name="gsm[]" placeholder="GSM" required onkeypress='return event.charCode >= 48 && event.charCode <= 57'/>
</div>
当按下 + 按钮时,它会添加新元素。这非常有效:
$(function() {
$("#addMore").click(function(e) {
e.preventDefault();
// Get the element of prisplan
var itm = document.getElementById("prisplan");
// Copy the element and its child nodes
var cln = itm.cloneNode(true);
// Append the cloned element to list
document.getElementById("fieldList").appendChild(cln);
$("#fieldList").append("<input type='text' placeholder='GSM' name='gsm[]' required onkeypress='return event.charCode >= 48 && event.charCode <= 57'>");
});
});
现在我还想要一个删除按钮。该按钮应该从“addMore”按钮中删除最后添加的元素,但永远不要删除原始元素。我怎样才能做到这一点?下面的代码是我到目前为止所得到的,但这会删除所有内容。
$(function() {
$("#removeMore").click(function(e) {
e.preventDefault();
$('#fieldList').remove();
});
});
我怎样才能做到这一点?
【问题讨论】:
-
为什么不在每个新输入字段旁边添加一个删除按钮?
-
为新添加的按钮添加一个类或一些属性,然后删除它的最后一次出现
-
@Mr.Polywhirl 你的意思是在
$("#removeMore").click(function(e) {中加一个吗? -
@AndreaSeliz 看看我的回答,可能是您正在寻找的解决方案。
标签: javascript html