如何对通过模板生成的按钮使用onclick事件?

时间:2012-12-31 12:53:26

标签: javascript jquery underscore.js

测试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和一个按钮。 但是当我点击按钮时没有任何事情发生。我是否错误地使用了听众?我希望在按钮点击上执行操作。请指教。

2 个答案:

答案 0 :(得分:3)

将委托与.on()

一起使用
$(function(){
    $(document).on('click','#helloAgain',function(event){
        event.preventDefault();
        alert('hello again bro!!!');
    });
});

答案 1 :(得分: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!!!');
    });

});