gpt4 book ai didi

javascript - 动态表格行,将点击事件委托(delegate)给新添加的元素

转载 作者:搜寻专家 更新时间:2023-10-31 22:40:51 26 4
gpt4 key购买 nike

首先只想说,我经历过几乎所有类似的问答,但没有任何解决方案和建议对我的情况有帮助。

我有这个结构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>');
});
});

最佳答案

您的事件委托(delegate)不正确。尝试如下。

$(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();
}
});

UPDATED FIDDLE

关于javascript - 动态表格行,将点击事件委托(delegate)给新添加的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36766212/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com