0

テストunderscore.js。テンプレートエンジンを使用します。jquery.AJAX問題は、ボタンがテンプレート内から描画されたときに書き込まれるオンクリックリスナーを使用できないことです。ここにコードがあります:

<script type="text/javascript" src="js/jquery-1.8.1.js"></script>
<script type="text/javascript" src="js/underscore.js"></script>


<div id="HelloWorld">
    <h1>Hi There</h1>
    <a href="" id="helloThere">Say Hello</a>
    <div id="helloDiv"></div>
</div>

<script>
    $('a#helloThere').click(function(event){
        event.preventDefault();
        var name='rickesh';
        var templateData=$('#sayHello').text();
        var compiled=_.template(templateData,{'data':name});
        $('#helloDiv').html(compiled);
    });

    $('button#helloAgain').click(function(event){
        event.preventDefault();
        alert('hello again bro!!!');
    });
</script>

<script type="text/html" id="sayHello">
    Hello <%= data%> <br />
    <button id="helloAgain">Say Hello Again</button>
</script>

さて、上記のコードで SAY HELLOリンクをクリックする<a href="" id="helloThere">Say Hello</a>と、テンプレートが正常に描画されHello rickesh、ボタンとともに表示されます。しかし、ボタンをクリックしても何も起こりません。リスナーを間違って使用しましたか?ボタンクリックでアクションを実行したい。ご意見をお聞かせください。

4

2 に答える 2

3

委任を使用する.on()

$(function(){
    $(document).on('click','#helloAgain',function(event){
        event.preventDefault();
        alert('hello again bro!!!');
    });
});
于 2012-12-31T12:56:27.907 に答える
1

おそらく次のように、html要素を作成した後にイベントリスナーを作成する必要があると思います。

$('a#helloThere').click(function(event){
    event.preventDefault();
    var name='rickesh';
    var templateData=$('#sayHello').text();
    var compiled=_.template(templateData,{'data':name});
    $('#helloDiv').html(compiled);

    $('button#helloAgain').click(function(event){
        event.preventDefault();
        alert('hello again bro!!!');
    });

});
于 2012-12-31T13:02:14.413 に答える