[英]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.