javascript - 动态创建的按钮和它自己的值
问题描述
如何获得data-index
点击按钮:
var removePair = $("button[name=removePair]"),
tbody = $('tbody[name=tb-table]'),
function DrawHtml(list) {
var html = '';
for (var i = 0; i < list.length; i++) {
var o = list[i];
html += '<tr name="row-' + i + '">';
html += ' <td>';
html += ' <button name="removePair" data-index="' + i + '" class="btn btn-primary mx-1" type="button"><i class="fa fa-trash-o" aria-hidden="true"></i></button>';
html += ' </td>';
html += '</tr>';
}
return html;
}
$(tbody).on("click", removePair, function () {
console.log($(this));
console.log($(this).val());
console.log($(removePair));
});
我知道在动态添加的按钮上添加事件的唯一方法是将其附加到parrent(tbody
),并通过动态创建的按钮触发removePair
,但我不知道如何点击以获得removePair
进一步的逻辑。
this
返回tbody
而不是removePair
谢谢!!
解决方案
您应该将选择器传递给.on()
方法而不是元素。由于元素是动态创建的,因此$("button[name=removePair]")
不存在。
采用
removePair = "button[name=removePair]"
var removePair = "button[name=removePair]",
tbody = $('tbody[name=tb-table]');
function DrawHtml(list) {
var html = '';
for (var i = 0; i < list; i++) {
html += '<tr name="row-' + i + '">';
html += ' <td>';
html += ' <button name="removePair" data-index="' + i + '" type="button">' + i + '</button>';
html += ' </td>';
html += '</tr>';
}
return html;
}
//Create HTML
tbody.html(DrawHtml(5));
$(tbody).on("click", removePair, function() {
console.log($(this).text());
console.log($(removePair).length);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tbody name="tb-table"></tbody>
</table>
推荐阅读
- java - 在 webService 上调用 jni4net 时出错,URI 方案不是“文件”
- javascript - 在 TypeScript 中使用“替代模式”混合
- python - 如何分发 Python 虚拟环境?
- javascript - React hook useState 改变一个常量数组
- angular - 不管 observables 是否存在都运行代码,但如果存在则等待它们?
- terraform - 我可以扩展在单独的 terraform 配置中声明的同名映射资源吗
- sql - 如何避免 SQL 中的联接并仍然跨表关联值
- docker - 无法在 nifi docker 中调用/写入文件:权限被拒绝问题
- r - 我可以要求 R 识别数据框的名称,然后将该名称添加到同一数据框中的列中吗?
- amazon-web-services - PuppeteerSharp on aws lambda net-core 3.1 执行错误