2016-12-17 13 views
1

誰かが私を助けることができますか? アイデアは、ループを備えたダイナミックなボタンを作成して、あなたはダイナミックボタンクリックイベントのライブ機能を使用する必要があり、それらの1jqueryの動的クリック機能

//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

あなたは '$(文書).onを( 'クリック'、+ i」は '#追加' 機能(E){...}を使用することになるでしょう) 'と呼びます。 [委任されたイベント](http://stackoverflow.com/documentation/jquery/1321/events/7666/delegated-events#t=201612170400446260567)に関するSOのドキュメントを参照できます。イベントハンドラを動的要素に具体的に追加する例がありましたが、これは決して受け入れられたり削除されたりしませんでした。いずれにしても、ドキュメントの例で '$( 'ul')'から '$(document)'に変更するだけです。 –

+0

代理人を使用します。 – Nadeem

答えて

0

を試してみてください。むしろ、ループが終了したときに値1000を取る変数iを常に参照します。おそらく、以下のようにボタンの属性に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

を使用するためにjqueryのクリック機能を使用することです。あなたのクリックハンドラの....iを入れた場合はクリックハンドラを作成したとき、それが何だったかにその値を修正されません。この

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

['live()'](http://api.jquery.com/live/)は廃止されました。また、$(document).on(click:function(){}、 '#add' + i) 「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 
}); 
関連する問題