测试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
以及一个按钮。 但是当我点击按钮时什么也没有发生。我是否错误地使用了监听器?我想要在单击按钮时执行操作。请指教。
最佳答案
通过 .on()
使用委托(delegate):
$(function(){
$(document).on('click','#helloAgain',function(event){
event.preventDefault();
alert('hello again bro!!!');
});
});
关于javascript - 如何对通过模板生成的按钮使用 onclick 事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14101858/