[英]Jquery click event doesn't fire with Handlebars template
I have a problem with Jquery .on() function and Handlebars template. 我对Jquery .on()函数和Handlebars模板有问题。 I wroted Handlebars template and add him dynamically in document:
我编写了Handlebars模板,并在文档中动态添加了他:
$('.services-wrapper').append(serviceTemplate({index : ++maxIndex}));
This template has a button: 该模板具有一个按钮:
<p>
<?= Html::buttonInput('Delete', [
'class' => 'btn btn-danger delete-service',
'id' => 'js-delete-service',
'data' => [
'index' => $index,
],
]) ?>
</p>
So I wroted click handler on this button: 因此,我在此按钮上编写了点击处理程序:
$('.service').on('click', '.delete-service', function (e) {
alert('Clicked');
//$(this).parent().parent().remove();
});
When I add this template to document, click event doesn't fire. 当我将此模板添加到文档中时,不会触发click事件。 What is the problem?
问题是什么?
您可能需要一个最接近的父包装器,例如:
$('.service-wrapper').on(...);
You try to attach the event handler to an element which doesn't exists in your DOM structure. 您尝试将事件处理程序附加到DOM结构中不存在的元素。 Before adding
on('click')
try to console log $('.service')
. 在添加
on('click')
之前on('click')
尝试控制台$('.service')
日志。 You need to use event delegation: https://learn.jquery.com/events/event-delegation/ So in your case: 您需要使用事件委托: https : //learn.jquery.com/events/event-delegation/因此,在您的情况下:
$( ".service-wrapper" ).on( "click", ".delete-service", function( event ) {
event.preventDefault();
alert('Clicked');
});
$("body").on('click','.delete-service',function(){
alert('Clicked');
});
Try this 尝试这个
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.