var i = 1;
$('.button').click(function() {
$('<br/><input name="name' + (++i) + '" type="text"/>').insertBefore(this);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>
<input name="name1" type="text" /><button class="button">+</button>
</div>
如何放置带有 [+] 加号按钮的按钮,以及何时单击它。按钮删除该字段。
最佳答案
只需在您的 HTML 字符串中添加一个新的按钮模板和一个包装 <div>
识别行。然后使用事件委托(delegate)绑定(bind)到动态创建的删除按钮上:
var i = 1;
$('.button').click(function() {
// Wrap each row in a div. Won't need a <br> to create a line break and it's styleable
$('<div><input name="name' + (++i) + '" type="text"/><button class="remove">-</button></div>').insertBefore(this);
});
// We need to use event delegation here, as the remove buttons are dynamically generated
$(document).on("click", ".remove", function() {
// Remove the parent, which is the rows <div> element
$(this).parent().remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="button">+</button>
关于javascript - 如何通过 Javascript 删除输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31913821/