【问题标题】:Can't use jquery to target elements rendered with Mustache.js无法使用 jquery 来定位使用 Mustache.js 呈现的元素
【发布时间】:2014-03-20 22:24:09
【问题描述】:

我有问题

我用 Mustache.js 创建了一个模板(示例):

<script type="text/template" id="info">
  <div id="info-content">
    {{>photoEl}}                
  </div>
</script>

某些元素被创建并添加为部分(示例):

partials.photoEl = '<span class="photo"><a class="button" href="#"></a></span>';

但我无法使用 jQuery 定位任何元素。

$('.button').click(function(event){
  console.log('click');
});

什么都不做……

知道为什么吗?

【问题讨论】:

  • 为什么你的div在脚本标签o.o里面?如果您要添加处理程序,则该元素不在 DOM 中,您需要向 .button 添加一个委托事件,因为它是在 DOM 由 mustache 准备好之后创建的(如果已创建)。

标签: jquery templates mustache


【解决方案1】:

使用event delegation 这将为将来的元素添加处理程序。

如果您使用 $(".button") 并且该元素不在 DOM 中,则事件处理程序将无法工作,因为会选择注释

$(document).on("click",".button",function(){
  console.log('click');
})

【讨论】:

  • 谢谢!我认为它必须与模板不是 DOM 的一部分有关......
  • 嗯,希望对你有所帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-05-16
  • 2016-05-07
  • 2020-05-30
  • 1970-01-01
  • 2021-02-11
  • 2021-08-19
  • 2016-07-01
相关资源
最近更新 更多