Async page transition question from node.js to ajax.

Asked 2 years ago, Updated 2 years ago, 51 views

        $('#myInfoCancel').click(function(e){
            $.ajax({
                type: "post",
                url: "/leftmenu",
                success: function(result,status,xhr){
                    $("#leftSection").html(result)
                },
                error: function(xhr, status, er){}
            });
            e.preventDefault();         
        });

Click the myInfoCancel button and click leftmenu.ejs in the leftSection

     res.render('account/leftmenu' , { layout:false });

I sent it in this form and sprayed it. The problem is that the page is sprayed like that, so there was no action because the existing jquery events did not recognize the part that was sprayed on the left section.

So inside the left menu.ejs,

    <script src="/javascripts/main.js"></script>

After writing it again, the action is now taking place, but the same event occurs twice because it overlaps with what was on the original page. What should we do in this case?

node.js ajax jquery

2022-09-22 08:31

1 Answers

The root cause of the problem is $("#leftSection") after importing html into Ajax.No events were set for elements added with html(result). That's why the event didn't respond.

After that, main.js is added and the event takes 2 times each because main.js is probably already sung once in layout.ejs.

As the layout page was loaded, main.js would have been called to set events for each element, leftmenu.The event must have been registered once again as main.js included in ejs was called.

Multiple events are registered in one element.

The most accurate solution to the above problem is to use Event deregistration.

Instead of placing an event on an element that is added dynamically, you set an event (click, etc.) on the element parent element and report the properties of srcElement or target set in the event object to determine its behavior.

If you don't understand after looking at the link above, please ask me again :)


2022-09-22 08:31

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.