对 JQuery 非常陌生,我在我的应用程序中集成了一个数据表。 我在最后一列中添加了两个按钮,但面临着将其与特定事件绑定(bind)的问题。
这是我生成表格最后一列的代码。
"mRender": function (data, type, full) {
console.log('>>>>>>>>>>><<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<');
console.log(full);
if(full.status) {
return '<button href="#"' + 'id="'+ data + '">Edit</button> <input type="button" href="#"' + 'id="disable-'+ data + '" value="Disable"></input>';
}
else {
return '<button href="#"' + 'id="'+ data + '">Edit</button> <input type="button" href="#"' + 'id="enable-'+ data + '" value="Enable"></input>';
}
}
根据状态,我显示启用/禁用按钮。
现在我想使用 JQuery 绑定(bind) onclick 事件。
我使用以下方式绑定(bind)了一个按钮。
$('#tenantTable tbody').on( 'click', 'button', function () {
var data = table.row( $(this).parents('tr') ).data();
});
$('#tenantTable tbody').on( 'click', 'input[id="enable*"]', function () {
var data = table.row( $(this).parents('tr') ).data();
console.log('>> DISABLE <<');
});
$('#tenantTable tbody').on( 'click', 'input[id="disable*"]', function () {
var data = table.row( $(this).parents('tr') ).data();
console.log('>> DISABLE <<');
});
它不起作用,有什么办法可以做到上述吗?
最佳答案
这种方式的 on()
方法是委托(delegate)事件处理程序的不错选择。
但是,您使用的选择器参数应该稍作更改:
$('#tenantTable tbody').on( 'click', 'input[id*="enable"]', function () {
// logic
});
$('#tenantTable tbody').on( 'click', 'input[id*="disable"]', function () {
// logic
});
*=
选择器会转换为 contains 选择器。
您的解决方案的替代方案可能是 startswith 选择器 ^=
此逻辑使得动态 ID 成为可能,例如:
<input type="button" id="enable-5" data-action="enable" data-id="5" value="my button" />
选择器可能类似于:
$(element).on('click', '[id^="enable-"]', function(){/*this: element where the id starts with enable-*/});
$(element).on('click', '[data-action="enable"]', function(){/*this: element where the data-action equals to enable*/});
$(element).on('click', '[data-id]', function(){/*this: element where data-id is defined*/});
关于javascript - JQuery Datatable 在将多个事件与单行中的多个按钮绑定(bind)时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43755872/