首页 > 解决方案 > 带有 HANDLEBARS 模板的按钮不会触发事件

问题描述

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

模板

<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 页面时,相同的按钮工作正常。你能帮我解决这个问题吗??

标签: jqueryhtmlhandlebars.js

解决方案


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

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

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


推荐阅读