Answer the question
In order to leave comments, you need to log in
How to make jq process new created html?
The point is. The script, when clicking on mleft, receives a response from the server and creates a second menu. The getTable function works with the second menu received, but it only fires once for some reason. That is, when the menu is first created - everything works, the class is assigned, when this menu is created the second time - nothing works. How to be?
$(document).ready(function(){
$('.mleft').on('click',function(){
$('.mleft').removeClass('action');
$(this).addClass('action');
let left = $(this).data('left');
$.ajax({
type: 'POST',
url: '/view-main',
data: {
left: left
},
success:function(items){
$('.button-main').hide('slow',function(){
$('.main-menu > nav > ul').empty();
items.main.forEach(function(body){
$('.main-menu > nav > ul').append('<li class="mmain" data-main="' + body.id + '">' + body.name + '</li>');
});
});
$('.button-main').slideToggle('slow');
getTable();
},
error:function(err){
console.log(err);
}
});
});
function getTable(){
$('.mmain').on('click',function(){
$('.mmain').removeClass('action-m');
$(this).addClass('action-m');
});
}
});
Answer the question
In order to leave comments, you need to log in
track through document
$(document).on('click','.mmain',function(){...}
Read https://api.jquery.com/on/ for the Direct and delegated event handlers section . In order for the event to be handled for newly created page elements, the handler must be bound to a parent element, such as a document, and the destination element selector must be specified in the call to the on()
. That is, in your case, you need a delegated type handler .
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question