[英]how to properly make a count function work for all the dynamically generated buttons?
I was writing a code to add 1 every time a button is pressed also the button is dynamically generated so are the table rows.我正在编写代码,每次按下按钮时加 1,按钮是动态生成的,表格行也是动态生成的。 the problem is i cant make the function work properly if there are second or third any other rows.
问题是如果有第二行或第三行,我无法使 function 正常工作。 I know the problem is that every button has the same class hence the count will always picks up where the other button left off.
我知道问题是每个按钮都有相同的 class 因此计数将始终从另一个按钮停止的地方开始。
$("form").submit(function(e){
e.preventDefault();
var name = $("input[name='name']").val();
$(".data-table tbody").append("<tr data-name='"+name+"' class='vote'><td>"+name+"</td><td><button class='but' id="+name+">VOTE</button></td><td><button class='btn btn-info btn-xs btn-edit'>Edit</button><button class='btn btn-danger btn-xs btn-delete'>Delete</button></td><td></td></tr>");
$("input[name='name']").val('');
});
// the code to count
let count = 1;
$("tbody").on("click", ".but", function(){
$(this).parents("tr").find("td:eq(3)").html('<span>'+count+'</span>');
return count++;
});
to be clear...... #1 Name button count john 4 jane 0要清楚...... #1 Name button count john 4 jane 0
#2 after one press of button on jane Name button count john 4 jane 5 i want to be able to count the number on Jane from 1 when pressed on her corresponding button #2 在 jane 上按一下按钮后 Name button count john 4 jane 5 我希望能够在按下相应按钮时从 1 开始计算 Jane 上的数字
also i'm trying not to use any plugins我也尽量不使用任何插件
and Thank you for helping.谢谢你的帮助。
First replace首先更换
`<button class='but' id="+name+">VOTE</button> `
with和
<button class='but' id="+name+" data-count="clicked-0">VOTE</button>
now your count code现在你的计数代码
$("tbody").on("click", ".but", function() {
let obj = $(this);
let clicks = obj.attr('data-count').replace('clicked-','');
clicks++;
obj.attr('data-count','clicked-'+clicks);
obj.parents("tr").find("td:eq(3)").html('<span>' + clicks + '</span>');
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.