gpt4 book ai didi

javascript - jquery动态点击函数

转载 作者:太空宇宙 更新时间:2023-11-04 16:14:16 25 4
gpt4 key购买 nike

有人可以帮助我吗?想法是创建带有循环的动态按钮,然后使用 jquery click 函数来使用其中之一

//I'm creating dynamic buttons like this:

for(i=0; i<1000; i++){
$contentBox.append('<button id="add'+ i +'" type="button" class="btn btn-success">Accept</button>');

//but how would I create the jquery click function?

$('#add'+i).click(function(e) {....});

//this does not create 1000 click functions. It only changes the id to the last one so what ever button you click on you will always get the las id
}

最佳答案

@Spencer 的评论很重要 - 您可以使用委托(delegate)事件。或者,您可以简单地使用按钮类:

for(i=0; i<1000; i++){
$contentBox.append('<button id="add'+ i +'" type="button" class="btn btn-success">Accept</button>');

//Rest of your code
}

//Then attach the event to the class:
$('button.btn-success').click( function(){
//I suspect you'll want the ID so here goes
var buttonID = $(this).attr('id');
//The rest of the fun stuff
});

关于javascript - jquery动态点击函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41195222/

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