【问题标题】:jQuery .click() won't fire from an <a> within a mustache.js templatejQuery .click() 不会从 mustache.js 模板中的 <a> 触发
【发布时间】:2013-12-05 16:01:00
【问题描述】:

我正在试验 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>

正如您在上面看到的,点击任何地方的链接都会触发警报。有什么想法吗?

【问题讨论】:

  • 一旦元素被添加到 DOM,你必须绑定事件,否则你的选择器返回 jquery 空对象。或将事件委托给任何静态祖先

标签: javascript jquery html templates mustache


【解决方案1】:

由于您使用的是模板语言,因此将动态创建元素,因此请尝试event delegation

$(document).on("click", "a", function () {
    alert("An <a> tag has been clicked on...")
});

【讨论】:

    【解决方案2】:

    因为当代码运行以附加点击时,锚点需要位于页面上。

    $(document).on("click", "a", function(){
      alert("An <a> tag has been clicked on...")
    });
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-22
    • 1970-01-01
    • 1970-01-01
    • 2014-11-25
    • 2011-02-27
    • 1970-01-01
    相关资源
    最近更新 更多