次のように、空の div があります。
<div id="my-content"></div>
次に、次のようなjQueryがあります。
/**IGNORE THIS**/
function makeButton(){
$('#my-content').html('<input type="button" value="Say hey" id="my-button" />');
}
ここまでは順調ですね。それから私はこのjsを持っています:
$(document).ready(function(){
makeButton();
});
完璧に動作しますが、この後、このボタンのトリガーを作成すると、次のようになり、ボタンIDに応答しません...
$(document).ready(function(){
makeButton();
$('#my-button').click(function(){
alert('Hello!');
});
});
<script>$(document).ready... blah... alert('Hello');</script>
もちろん、makeButton 関数の .html() に追加することもできますが、それは実際の方法ではないと思います。
makeButton() の準備ができてボタンが追加された後、クリックのリッスンを開始するように JS に指示するにはどうすればよいですか?
編集:わかりました、それはうまくいきます。ごめん。実際のケースは上記とは異なりますが、似ています。
makeButton() は、実際には ajax によってデータを取得する別の関数であるため、makeButton は次のようになります。
makeButton(){
$.ajax({
type: 'POST',
url: 'ajax_images.php',
data: {pageNr: pageNr},
success:function(response) {
//Loops the json and does something like this:
var HTML = '<div id="thumbnail">;
HTML += 'Response Stuff'
HTML += '</div>';
$('#my-content').html(HTML);
}
});
}
混乱させてすみません。