有人可以帮助我吗? 想法是使用循环创建动态按钮,然后使用jquery单击功能来使用其中一个
//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
}
答案 0 :(得分:1)
@ Spencer的评论很重要 - 您可以使用委托活动。或者,您只需使用按钮类:
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
});
答案 1 :(得分:0)
您应该使用实时功能进行动态按钮点击事件。试试这个
$('#add'+i).live("click", function(){
// codings
});
答案 2 :(得分:0)
如果您将i
放在点击处理程序的....
中,则无法将其值修复为创建点击处理程序时的值;相反,它总是会引用变量i
,它在您完成循环时获取值1000
。也许您可以将i
存储在按钮的属性中,如下所示(或者从元素的ID中读取)。
$contentBox = $('#content');
$result = $('#result');
for(i=0; i<10; i++){
$contentBox.append('<button id="add'+ i +'" data-eyeVal="' + i + '" type="button" class="btn btn-success">Accept</button>');
//but how would I create the jquery click function?
$('#add'+i).click(function(e) {$result.append('<br/>clicked ' + $(this).attr('data-eyeVal'))});
//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
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="content"></div>
<div id="result"></div>
&#13;