javascript - 从 DIV 中删除元素以及之前插入的值

标签 javascript jquery html

我之前在页面中克隆一些 HTML 时遇到了问题,现在我已经使用下面的 JS Fiddle 解决了该问题:

HTML:

<div id='1'>
    <div class="template"> <!-- mark a clone target -->
        ...
    </div>
    <div>
        <input type="button" name="addNewRow" value="Add Row" />
    </div>
</div>
JS:

var $template = $('.template');
$('input[type=button]').click(function() {
    $template.clone().insertAfter($template);
});

演示:http://jsfiddle.net/VcBrz/

编辑**我在克隆和清除​​文本框时遇到的第一个问题已经解决。

如果您引用上面的 JSFiddle - 每次单击表单上的按钮时都会添加一个新行。 我希望添加另一个按钮来实现完全相反的效果,因此可以在单击按钮时删除行,并且想知道是否有人可以提出答案?

最佳答案

尝试以下操作

var $template = $('.template');
$('#add').click(function() { // where add is the id of add button
 $template.clone().insertAfter($template).find("input:text").val("");
});
$('#remove').click(function() { // where remove is the id of remove button
if($('.template').length>1)
 $('.template').last().remove();
});

检查这个JSFiddle

关于javascript - 从 DIV 中删除元素以及之前插入的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23019682/

相关文章:

php - Titanium Mobile/Javascript Json 调用不起作用

javascript - jQuery - 如何通过动态表中的文本框显示下拉选定的值

javascript - 显示加载程序直到幻灯片完全加载

javascript - 摆脱链接标签?

javascript - 通过表单上传文本和图像

javascript - 只有第一个弹出框在工作

javascript - 如何为使用window.open打开的新窗口指定外部js和css

html - 如何将三个 div 合并为一个以共享背景?

facebook - 我应该在 head 标签中添加什么

javascript - 在外部 .js 文件中使用 .vue 组件时如何使用相同的变量?