2016-12-17 114 views
1

有人可以幫我嗎? 的想法是創建一個循環的動態按鈕,然後使用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

回答

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 
 
}
<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')」 –

0

你應該使用實時功能動態按鈕點擊事件。試試這個

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

['live()'](http://api.jquery.com/live/)已被棄用,從'1.9'開始刪除。 –

1

@斯賓塞的評論是點 - 您可以使用委派事件。或者,您可以簡單地使用按鈕類:

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