html - jquery - 从克隆的 html 中替换一个元素
问题描述
我想实现以下两种情况:
需要在单击加号按钮时添加行。
需要用动态添加的行中的超链接替换加号按钮。
<button type="button" class="addRow" />+</button>
对于所有动态添加的行,将上面的按钮替换为下面的按钮。
<a href="javascript: void(0)" title="Click to remove">Remove</a>
我已经完成了第一个场景并坚持使用第二个场景。
HTML:
<table id="exampleTbl">
<tr>
<td>1</td>
<td>2</td>
<td>
<button type="button" class="addRow" />+</button>
</td>
</tr>
<tr>
<td>3</td>
<td>4</td>
<td>
<button type="button" class="addRow" />+</button>
</td>
</tr>
</table>
jQuery:
$(function() {
$('#exampleTbl').delegate('button.addRow', 'click', function() {
var row = $(this).closest('tr'); // get the parent row of the clicked button
var html = $(this).closest('tr').clone();
$(html).insertAfter(row); // insert content
});
});
解决方案
你可以试试这个。
$(function() {
$('#exampleTbl').delegate('button.addRow', 'click', function() {
var row = $(this).closest('tr'); // get the parent row of the clicked button
var html = $(this).closest('tr').clone();
$(html).insertAfter(row); // insert content
let btn = $('<a href="javascript: void(0)" title="Click to remove">Remove</a>');
btn.click(function () {
$(html).remove(); // Remove row on click
})
$(html).find('.addRow').replaceWith(btn);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="exampleTbl">
<tr>
<td>1</td>
<td>2</td>
<td>
<button type="button" class="addRow">+</button>
</td>
</tr>
<tr>
<td>3</td>
<td>4</td>
<td>
<button type="button" class="addRow">+</button>
</td>
</tr>
</table>
工作 JSFiddle:https ://jsfiddle.net/j18yfwLv/1/
注意:我刚刚将按钮替换为您想要的内容,您是否希望按钮也删除该行?
推荐阅读
- python-3.x - 使用 python 调用脚本后,对 mpirun 的 os.system() 调用不起作用
- retrofit - 如何在php中接受随机数量的上传文件?
- java - 在 JNI 中,如何从 C++ 访问 Java 中 JSONObject 的值,将一些值放入其中并返回?
- express - 为什么 app.use 之后定义的路由在获取请求后没有返回任何内容?
- swift - 如何在按钮单击时在 uimageview 中显示不同的图像
- c# - MsTest 并行化
- javascript - 从模块导入类
- forms - 使用 appBar 图标打开表单
- scala - 在Scala中使用模式匹配的匹配子句中的对象
- python - 如何在 python 中使用 tensorflow 后端解决错误