U
U
urajo2020-04-18 21:14:52
JavaScript
urajo, 2020-04-18 21:14:52

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

2 answer(s)
T
ThunderCat, 2020-04-18
@ThunderCat

track through document
$(document).on('click','.mmain',function(){...}

M
Mikhail Ushenin, 2020-04-19
@usheninmike

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 question

Ask a Question

731 491 924 answers to any question