【问题标题】:The buttons present withing the HANDLEBARS templates are not firing the eventsHANDLEBARS 模板中的按钮不会触发事件
【发布时间】:2018-08-29 21:03:15
【问题描述】:

我试图为车把模板中的按钮提供点击事件。但这些事件并没有被解雇。请在下面找到代码:

模板

<table class="table shadow p-3 mb-5 bg-white rounded">
        <thead class="thead-dark">
          <tr>
            <th scope="col">NAME</th>
            <th scope="col">EMAIL</th>
            <th scope="col">DOB</th>
            <th scope="col">DEPT</th>
            <th scope="col">GENDER</th>
            <th scope="col">AGE</th>
            <th scope="col"></th>
            <th scope="col"></th>
          </tr>
        </thead>
        <tbody>
            {{#each ALL_RECORDS}}
          <tr>
            <td scope="row">{{this.name}}</td>
            <td scope="row">{{this.eMail}}</td>
            <td scope="row">{{this.DOB}}</td>
            <td scope="row">{{this.dept}}</td>
            <td scope="row">{{this.gender}}</td>
            <td scope="row">{{this.age}}</td>
            <th scope="row" style="text-align: center"><button class="btn btn-primary" type="button" name="EDIT_BTN">EDIT</button></th>
            <th scope="row" style="text-align: center"><button class="btn btn-danger"  type="button" name="DEL_BTN">DELETE</button></th>   
          </tr>
          {{/each}}
        </tbody>
      </table>

jQuery

​​>
$("[name='DEL_BTN']").click(function(){
    alert("DELETE BUTTON CLICKED");
})

点击删除按钮时,它不会触发警报。 从模板移出到 HTML 页面时,相同的按钮工作正常。你能帮我解决这个问题吗??

【问题讨论】:

  • 在绑定事件时您的按钮可能不存在尝试从不是由把手生成的父元素委托事件,例如:$('.table').on(' click', 'button' , function(e){ //do stuff });
  • @digital-pollution 这行得通。非常感谢……

标签: jquery html handlebars.js


【解决方案1】:

尝试在您的函数周围添加 $(document).ready() 以便您的模板将被渲染并插入到 DOM 中。

$(document).ready(function(){
   $("[name='DEL_BTN']").click(function(){
       alert("DELETE BUTTON CLICKED");
   })
});

我认为您的问题是在您启动 jquery 函数时事件未绑定到您的按钮。如果您不想使用 $(document).ready 方法,只需确保在使用选择器并启动警报之前已评估您的车把模板并将其插入 DOM。

【讨论】:

  • 感谢您的回答,但我已经尝试添加 $(document).ready ,但即使单击按钮也不起作用。你能帮我么。我完全被困在这里......
  • @METALHEAD 首先在您的控制台中,您是否尝试过 console.log($("[name='DEL_BTN']"));在您尝试添加点击事件的同时?
  • 在尝试控制台时,我得到的输出是 w.fn.init [prevObject: w.fn.init(1)] length:0 prevObject:w.fn.init [document] __proto__:Object(0)
  • 试试这个 $("[name='DEL_BTN']").each(function(a,b){console.log(b);}) 这应该显示按钮的 html 代码.如果它不显示任何内容,则表示您的模板尚未插入 DOM。如果尚未插入,则必须解释如何渲染模板,然后必须在模板渲染后移动代码。
  • 感谢@christophie 的所有指导。我已经使用代表来解决这个问题。谢谢。
猜你喜欢
  • 2017-08-25
  • 2012-10-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-19
相关资源
最近更新 更多