处理车把上的 jQuery onClick 事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17548265/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 19:17:01  来源:igfitidea点击:

handling jQuery onClick event on handlebars

javascriptjqueryhandlebars.js

提问by Hal

I would like to set up a simple jQuery onClick event to make the UI dynamic on a handlebars template. I was wondering to addClass() after a specific click.

我想设置一个简单的 jQuery onClick 事件,使车把模板上的 UI 动态化。我想知道在特定点击后 addClass() 。

consider the HTML (generated by handlebars)

考虑 HTML(由把手生成)

  {{#if hasButton}}
      <div id="container">      
          <button type="submit" class="myButton">Click me!</button>
      </div>
  {{/if}}

i.e: After a click within a button, its container will receive a loading class that will create the interaction using CSS.

即:在按钮内单击后,其容器将收到一个加载类,该类将使用 CSS 创建交互。

$(".myButton").on("click", function(event){
        $(this).parent().addClass("loading");
});

This code should goes on my handlebars-template or should I rewrite it into a specific helper for it? Is there any examples that could be provided so I can study it then develop something similar?

这段代码应该放在我的车把模板上,还是我应该将它重写为特定的帮助程序?是否可以提供任何示例,以便我可以研究它然后开发类似的东西?

Thanks in advance!

提前致谢!

回答by murnax

there is no need to reattach the event handler on every dynamic DOM update if you're defining them at document level:

如果您在文档级别定义它们,则无需在每个动态 DOM 更新上重新附加事件处理程序:

$(document).on('click','li',function(){
   alert( 'success' );
});

Hope this helps! :-)

希望这可以帮助!:-)

回答by Nicolas Delaforge

You have to refresh your Jquery listeners AFTER the insertion of nodes into your DOM HTML.

在将节点插入 DOM HTML 后,您必须刷新 Jquery 侦听器。

var source   = "<li><a href="{{uri}}">{{label}}</a></li>";
var template = Handlebars.compile(source);
var context = {"uri":"http://example.com", "label":"my label"};
$("ul").append( template(context) );

// add your JQuery event listeners
$("li").click(function(){ alert("success"); });

回答by glautrou

I am not sure what your problem exactly is. It's correct like this if you keep your JavaScript in a *.js file, perhapsusing parent() instead on prev()in this specific case.

我不确定你的问题到底是什么。如果您将 JavaScript 保存在 *.js 文件中,则在这种特定情况下perhaps使用 parent() 代替 on prev(),这是正确的。