我正在尝试使用Mustache.js,我无法从通过模板呈现的链接中触发.click()事件。
// click on tab to reveal information below
$(".tab").on("click", function(){
var name = $(this).attr('data-name');
var data = {"class":"lisa","name":"Lisa Jones","age":"http://lisajones.com","address":{"streetAddress":"88 High Street","city":"Birmingham","postCode":"B1 2AA"},"workNumber":"+44 1234 474747","contactableAtHome":false,"personalNumbers":[{"type":"tel","number":"+44 1234 111222"},{"type":"mobile","number":"+44 7987 444555"}],"biography":"lisa ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."};
var template = $('#infoContact').html();
var html = Mustache.to_html(template, data);
$('#content').html(html);
});
// everytime an a is clicked this should fire
$("a").on("click", function(){
alert("An <a> tag has been clicked on...")
});
</script>
<script id="infoContact" type="text/template">
<div class="side-panel">
<ul>
<li><a href="#">But if you click on this nothing happens...</a></li>
</ul>
</div>
</script>
如上所示,点击任意位置的链接都会触发警报。有什么想法吗?
答案 0 :(得分:2)
由于您使用的是模板语言,因此会动态创建元素,因此请尝试event delegation
$(document).on("click", "a", function () {
alert("An <a> tag has been clicked on...")
});
答案 1 :(得分:1)
因为当代码运行以便附加点击时,锚点需要在页面上。
$(document).on("click", "a", function(){
alert("An <a> tag has been clicked on...")
});