Mustache不能正确处理事件

我想用胡子在我的html文件中插入一些模板。

模板,jquery代码和html代码分为三个单独的文件。 这是强制性的,因为我希望我的项目能够尽可能多地组织起来。

当我将’nav’直接写入html文件时,click事件工作正常,但如果尝试用胡子插入它就会停止工作。 知道为什么吗? 谢谢。

test1.php文件

  World News     body{ background-color: #FFFFFF; position: absolute; top: 10%; left: 15%; right: 15%; } #menu ul li{ display:inline; padding: 0; margin: 0; }    

process1.js

  function Guardian_news(filter, selector, div) { this.path = 'fullwindow1.html'; this.filter = filter; this.selector = selector; this.populate = function(){ $.get(this.path, function(templates){ var template = $(templates).filter(filter).html(); $(selector).html(Mustache.render(template)); }); } } $(document).ready(function(){ var menu; menu = new Guardian_news('#navigationBar', '#menu'); menu.populate(); $('#science').click(function(){ alert('url accessed'); }); }); 

fullWindow1.html

     

问题是你将事件处理程序绑定到元素之前,因为它仍然是ajax。

尝试在Guardian_news包含一个回调函数,并在ajax完成后执行它 – 然后在该回调中绑定您的事件。

编辑:这样的事情:

 function Guardian_news(filter, selector, div, callback) { this.path = 'fullwindow1.html'; this.filter = filter; this.selector = selector; this.populate = function(){ $.get(this.path, function(templates){ var template = $(templates).filter(filter).html(); $(selector).html(Mustache.render(template)); callback(); // Call our callback here once the ajax is complete and the template is rendered }); } } $(document).ready(function(){ var menu; var callback = function () { $('#science').click(function(){ alert('url accessed'); }); } menu = new Guardian_news('#navigationBar', '#menu', callback); menu.populate(); }); 

使用on-handler而不是click 。 它看起来像这样:

  $(document).ready(function(){ var menu; menu = new Guardian_news('#navigationBar', '#menu'); menu.populate(); $('#menu').on('click', '#science', function(){ alert('url accessed'); }); }); 

您必须确保,您附加处理程序的元素已经存在。 使用选择器调用on ,确保它只处理特定元素。

有关更多信息,请参阅此小提琴 。