简体   繁体   中英

Calling a function from within itself

I have several elements inside a container. All their events are handled inside a function events() .

On click of a button inside the container, I replace the container's html with the response from an AJAX request.

function events() {
    $(".btn").on("click", function() {
     ...
    }); 

    $(".txt").on("keyup", function() {
     ...
    });

    $(".btn2").on("click", function() {
                var xmlhttp;
                if (window.XMLHttpRequest) {
                    xmlhttp = new XMLHttpRequest();
                }
                xmlhttp.onreadystatechange = function() {
                    if (xmlhttp.readyState == 4) {
                       $(".container").html(xmlhttp.responseText); 
                       events(); // ***
                    }
                }
                url = 'handlers/gethtml.ashx';
                xmlhttp.open("GET", url, true);
                xmlhttp.send(null);
        });
}

Now, I need to rebind all the controls with events so after changing the html $(".container").html(xmlhttp.responseText); I call the function within itself because the new html contains the same controls with the same events.

Does this cause stack overflow? I have some performance issues so i was wondering if this maybe the cause. Also, is there any workaround, maybe a more elegant way to do this?

Use event delegation, then no need to rebind the events since it will handle dynamic element as well

You could further shorten the code by using jquery to load the url contents

function events() {
    var ct = $(".container");
    ct.on("click", ".btn", function() {
    }); 

    ct.on("keyup", ".txt", function() {
    });

    ct.on("click", ".btn2", function() {
        ct.load('handlers/gethtml.ashx')
    }

Try using event delegation, you don't need to bind the event again

$(".container").on("click",".btn2", function() {...});

Just call events() . It is in the scope!

There are a couple of things you need to be aware of, though:

  1. Elements already on there will have two click handlers on the second run - the old, and the new. To get rid of them, use unbind to unbind all click events, for example.
  2. You may want to split up your event creation function further.

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