【问题标题】:Click event not working inside handlebar template单击事件在车把模板内不起作用
【发布时间】:2013-10-17 16:18:21
【问题描述】:

我的模板是这样的

{{#users}}
 <div id="userRoleInfo">
        <input type="hidden" id="userId" value="{{id}}" />
        <div class="label">
            <label>User permission</label>
        </div>

     <div class="user-item-right">
// I want to capture click event of this anchor tag
            <a href="#" class="updown-arrow" onClick="callUserDetail()" data-control="userBtn"><i class="icon-arrow-big"></i></a>
          </div>    

        {{#checkUser ../user.roleId roleId ../roles}}
            <div >Administrator</div>
        {{else}} 
            <select id="selRoleId" data-custom="true">                                                   
                    <option value="0" >Assign Role</option>

                {{#each roles}}
                    <option value="{{roleId}}">{{name}}</option>
                {{/each}}

            </select> 
        {{/checkUser}}

   </div>

 {{/users}} 

整个模板都附加在里面

 <div id="usersMgmtDiv" class="user-mngt-wrapper clearFix">
 </div>

我想在点击里面的锚标签时显示用户信息

  <div class="user-item-right"> 

我为点击事件写的函数是这样的

   japp.users.bindEdit = function () {

 if (jQuery('[data-control=userBtn]').size() === 0) {
    return;
 }

var self = japp;

jQuery('[data-control=userBtn]').each(function() {
    jQuery(this).live('click', function (e) {
        e.preventDefault();
        e.stopPropagation();
        if(jQuery(this).is('.active')){
            self.users.hideUserBox(jQuery(this));
        } else {
            self.users.showUserBox(jQuery(this));
        }
    });
});

但它不会进入这个函数

更新

我尝试使用像

这样的 javascript 方法调用
  function callUserDetail(){
japp.users.bindEdit();
}

但这需要点击 2 次才能完成

这应该有效还是有其他方法可以做到这一点。如果需要更多信息,请告诉我

【问题讨论】:

    标签: jquery templates handlebars.js


    【解决方案1】:

    你的问题就在这里:

    jQuery('[data-control=userBtn]').each(function() {
        jQuery(this).live('click', function (e) { /* ... */ });
    });
    

    当您尝试迭代它们时,页面上不会有任何 [data-control=userBtn] 元素。那些&lt;a&gt;s 直到您将填写的模板添加到页面后才会存在。此外,live 在 jQuery 1.7 中已被弃用,并在 1.9 中被删除,因此您不应再使用它,而应使用 on

    理想情况下,您应该有一个已知的容器,您可以将模板放入其中。然后你会说:

    $('#container').on('click', '[data-control=userBtn]', function(e) {
        // Deal with the click in here.
    });
    

    并将填写好的模板扔到#container

    演示:http://jsfiddle.net/ambiguous/PhtP3/

    如果你没有这样的容器,那么你可以使用on的live-ish形式:

    $(document).on('click', '[data-control=userBtn]', function(e) { ...
    

    演示:http://jsfiddle.net/ambiguous/ZaLnq/

    【讨论】:

    • 非常感谢伙计。它的工作完美,并通过示例进行了很好的解释
    猜你喜欢
    • 2023-03-20
    • 2022-08-09
    • 2014-04-16
    • 2021-04-18
    • 1970-01-01
    • 2018-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多