简体   繁体   中英

Jquery click event doesn't fire with Handlebars template

I have a problem with Jquery .on() function and Handlebars template. I wroted Handlebars template and add him dynamically in document:

$('.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. 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. Before adding on('click') try to console log $('.service') . You need to use event delegation: https://learn.jquery.com/events/event-delegation/ So in your case:

$( ".service-wrapper" ).on( "click", ".delete-service", function( event ) {
  event.preventDefault();
  alert('Clicked');
});
$("body").on('click','.delete-service',function(){
     alert('Clicked');
});

Try this

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM