jQuery .click()不会从<a> within a mustache.js template</a>触发

时间:2013-12-05 16:01:01

标签: javascript jquery html templates mustache

我正在尝试使用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>

如上所示,点击任意位置的链接都会触发警报。有什么想法吗?

2 个答案:

答案 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...")
});