[英]Dynamic table row, delegation of click event to newly added elements
首先,我只想提一下,我几乎已经完成了所有类似的问答,并且没有解决方案和建议对我有所帮助。
我有这个构造DEMO和下面的代码,向表中添加一个新元素。 我喜欢新元素,它是tr和td,具有与现有元素相同的功能。 我试过live()和delegate(),什么都行不通。 所有的建议和教程指向我已经使用的on()函数,但仍然不起作用。 我究竟做错了什么? 请高度赞赏任何建议。 下面的代码添加了新元素:
$(function(){
$('#add').on('click',function() {
$('#edit-tb tr:last').after('<tr><td><button class="up">Up</button></td><td><span class="times" data-myval="1"></span>Goe</td><td><button class="down">Down</button></td></tr>');
});
});
您的活动授权不正确。 尝试以下。
$(document).on('click', '.up', function () {
var count = $(this).closest('tr').find('.times').attr('data-myval');
count++;
if (count > 4) {
count--;
$('#max').modal('show');
$(this).closest('tr').find('.times').text(4 + ' x ');
}
$(this).closest('tr').find('.times').attr('data-myval', count);
$(this).closest('tr').find('.times').text(count + ' x ');
});
$(document).on('click', '.down', function () {
var count = $(this).closest('tr').find('.times').attr('data-myval');
count--;
parseInt($(this).closest('tr').find('.times').attr('data-myval', count))
$(this).closest('tr').find('.times').text(count + ' x ');
if (count < 2) {
$(this).closest('tr').find('.times').text('');
}
if (count < 1) {
$(this).parents('tr').remove();
}
});
事件委托在容器上捕获事件,但仅在目标元素或其父节点之一具有特定选择器时才调用回调。 要委派事件,请使用.on()
将事件附加到父.on()
,但添加第2个参数,该参数表示目标。 例如:
$('.table') // container
/* event , target, handler */
.on('click', '.up' , function() {});
如果希望绑定忽略标头,则应将事件处理程序附加到关闭容器, .table
或事件.table > tbody
。
演示( 小提琴 ):
$(function() {
$('.table')
.on('click', '.up', function() {
var element = $(this);
var count = element.closest('tr').find('.times').attr('data-myval');
count++;
if (count > 4) {
count--;
$('#max').modal('show');
element.closest('tr').find('.times').text(4 + ' x ');
}
element.closest('tr').find('.times').attr('data-myval', count);
element.closest('tr').find('.times').text(count + ' x ');
})
.on('click', '.down', function() {
var element = $(this);
var count = element.closest('tr').find('.times').attr('data-myval');
count--;
parseInt(element.closest('tr').find('.times').attr('data-myval', count))
element.closest('tr').find('.times').text(count + ' x ');
if (count < 2) {
element.closest('tr').find('.times').text('');
}
if (count < 1) {
element.parents('tr').remove();
}
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.