Javascript 事件委托未按预期工作
我在我的click事件中有一个模板,我在crurrent表行之后插入该模板,但问题是当您单击新添加的模板时,该模板具有一个名为“添加事件按钮”的类。添加事件将终止,不再工作。它仅在页面加载模板时工作一次Javascript 事件委托未按预期工作,javascript,jquery,Javascript,Jquery,我在我的click事件中有一个模板,我在crurrent表行之后插入该模板,但问题是当您单击新添加的模板时,该模板具有一个名为“添加事件按钮”的类。添加事件将终止,不再工作。它仅在页面加载模板时工作一次 $('.variations_grid tr td').delegate('.add', 'click', function(e) { $(this).closest('tr').after(template); //the buttons int the template do
$('.variations_grid tr td').delegate('.add', 'click', function(e) {
$(this).closest('tr').after(template);
//the buttons int the template don't work on click event
});
var template = '<tr>';
template += '<td class="white-space:nowrap">';
template += '<input type="hidden" name="variationsid" value="1" />';
template += '<button class="btn btn-default btn-block add" type="button"> <span class="glyphicon glyphicon-plus-sign"></span> </button>';
template += '<button class="btn btn-default btn-block remove" type="button"> <span class="glyphicon glyphicon-minus-sign"></span> </button>';
template += '</td>';
template += '<tr>';
$('.variations_grid tr td')。委托('.add','click',函数(e){
$(this).最近('tr')。在(模板)之后;
//模板中的按钮在单击事件上不起作用
});
var模板=“”;
模板+='';
模板+='';
模板+='';
模板+='';
模板+='';
模板+='';
对于事件委派,唯一需要注意的是,放置处理程序的DOM元素不能被替换。因此,您必须选择最接近的、不会被替换的容器
例如,如果要替换或添加新的
或
标记,请不要在这些标记上绑定事件处理程序,否则委派将不起作用
尝试此操作(我将delegate
替换为on
,因为delegate
现在已被弃用):
非常感谢你的帮助。我从你的回答中学到了一些东西我会记住的谢谢again@KDM很高兴我能帮忙。是的,这种方法也很有效。谢谢你的帮助
$('.variations_grid').on('click', '.add', function(e) {
//your logic
});