2012-12-31 67 views
0

測試underscore.js。使用其模板引擎。問題是,當按鈕從模板中繪製時,我無法使用單擊監聽器,使用jquery.AJAX編寫。下面的代碼:如何使用通過模板生成的按鈕使用onclick事件?

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

現在,在上面的代碼,當我點擊打招呼鏈接<a href="" id="helloThere">Say Hello</a>,模板是成功繪製並顯示Hello rickesh一個按鈕一起。 但是,當我點擊按鈕沒有任何反應。我是否錯誤地使用了監聽器?我想要對按鈕單擊執行一個操作。請指教。

回答

3

使用代表團.on()

$(function(){ 
    $(document).on('click','#helloAgain',function(event){ 
     event.preventDefault(); 
     alert('hello again bro!!!'); 
    }); 
}); 
+0

感謝很多:) –

1

我想你應該創建HTML元素後創建事件偵聽器,大概是這個樣子:

​​3210
相關問題