jquery动态点击功能

问题描述:

有人可以帮我吗? 的想法是创建一个循环的动态按钮,然后使用jQuery的点击功能,使用其中一个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

您将希望使用'$(document).on('click','#add'+ i',function(e){...} )'动态元素。你可以参考关于[委托事件]的SO文档(http://stackoverflow.com/documentation/jquery/1321/events/7666/delegated-events#t=201612170400446260567)。我有一个例子,特别是将事件处理程序添加到动态元素,尽管它从未被接受/删除。无论如何,只要将文件示例中的$('ul')'更改为'$(document)',它就可以在任何情况下工作。 –

+0

使用代表。 '$(document).on(click:function(){},'#add'+ i)' – Nadeem

如果您在点击处理程序的....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 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div id="content"></div> 
 
<div id="result"></div>

+0

你这个人。正是我想要的“$(this).attr('data-eyeVal')” –

你应该使用实时功能动态按钮点击事件。试试这个

$('#add'+i).live("click", function(){ 
    // codings 
}); 
+0

['live()'](http://api.jquery.com/live/)已被弃用,从'1.9'开始删除。 –

@斯宾塞的评论是点 - 您可以使用委派事件。或者,您可以简单地使用按钮类:

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