E
E
Evgeny Ivanov2018-02-15 14:14:47
JavaScript
Evgeny Ivanov, 2018-02-15 14:14:47

Why does the code only work once?

The page has a list of links

<a href="#" class="ui_link_2 delete_message_link" id="10">Удалить</a>
<a href="#" class="ui_link_2 delete_message_link" id="8">Удалить</a>


This code works on every click

$(document).ready(function() { 

$('.delete_message_link').on('click', function(){
alert('Сработало!');
return false;
});


});


This code only works once

$(document).ready(function() { 

$('.delete_message_link').on('click', function(){
$.ajax({
url: 'actions.php?delete_message&id='+this.id,
success: function(data){$('#messages_area').html(data);}
});
return false;
});

});


On the first click, the record is deleted in the database and data is returned to #messages_are.
On the second, nothing happens. The record in the database is not deleted, the data is not returned.
Those. the script is not called.

Why does the code only work once and how can I fix it?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
E
Egor Zhivagin, 2018-02-15
@logpol32

Show the html structure
. I'm almost sure that the solution would be to hang the handler like this:

$('#messages_area').on('click', '.delete_message_link', function(){

P
Philip Gaponenko, 2018-02-15
@filgaponenko

This happens for the following reason:
you are inside.
When the page is loaded, the script executes and hangs a handler on each element with the class: .delete_message_link
After that, you overwrite the content and, accordingly, there are no event handlers on the new elements. The solution could be to rehang the handlers after changing the content $('#messages_area').html(data);
$('#messages_area').html(data);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question