简体   繁体   中英

Is there a way to do global event binding on dynamic HTML loaded via jQuery .load()?

I have an HTML page that uses jQuery .load() to pull in HTML from other files. I do this mostly for readability purposes.

I ran into a problem whereby code that is loaded via .load() is not "visible" to other javascript loaded later in the module because .load() is asynchronous. This was solved in another StackOverflow question of mine with very good results, by doing the .click() binding in the .load() callback. SO shone through like it always does!

Now, I have another question that is also related.

HTML:

        <div class="mainContent" style="color:white; overflow-y: auto; position:fixed; top:210px; bottom:60px;">
            <div class="linkContent" id="contentAboutUs"        style="display:none"></div>
            <div class="linkContent" id="contentAboutUsCompany" style="display:none"></div>
            <div class="linkContent" id="contentAboutUsVerify"  style="display:none"></div>
            <div class="linkContent" id="contentAboutUsSelf"    style="display:none"></div>
            <div class="linkContent" id="contentAboutUsHow"     style="display:none"></div>
        </div>

jQuery ready() function:

$("#contentAboutUs").load("contentAboutUs.html");
$("#contentAboutUsCompany").load("contentAboutUsCompany.html");
$("#contentAboutUsVerify").load("contentAboutUsVerify.html");
$("#contentAboutUsSelf").load("contentAboutUsSelf.html", function () { $(".saveButton").click(function () { saveForm(); })  });
$("#contentAboutUsHow").load("contentAboutUsHow.html");

You will notice that on the AboutUsSelf .load(), a callback binds the click event of the ".saveButton" to a function called saveForm(). This works perfectly, and was the answer I got from my previous SO question.

As you see, ".saveButton" is a class, and in fact, this button will be on MANY pages of the form; which is why it is a class and not an ID.

The question then is this: I do not want to do this click() binding on every section that contains one of these buttons. Is there a way to dynamically .load() this HTML, and yet apply this click() binding globally instead of doing it in the .load() callback individually in every case where it is needed?

Since you are loading these inside a container, you can use that.

$('.mainContent').on('click','.saveButton', function(){
     saveForm();
});

Event handlers bound this way bind to the container and it "looks within" for the selector of the button. You cannot directly bind to the class for the button as it has nothing to bind to until it is loaded and in the DOM.

Bind to the closest container (not document for instance) that you can to avoid the deep "look within" impact with a super large DOM.

Note that one thing you also experience here is multiple hits to your sever - ie you would benefit from the cache of the HTML if it were in the page already and it only hits the page once that way. That being said, dynamic page portions are a good candidate for this type binding at the container level.

With ASP.NET MVC for instance these can be put in partial views and get in the page prior to hitting the browser.

You did not ask but I would also move the style to a CSS file and not put it in the markup - this then makes your markup much cleaner and easier to modify.

看看ajaxComplete-应该能够在其中附加click事件并将其应用于加载的所有新按钮

I believe what you are looking for is event delegation .

Essentially, what you can do is bind your event listener, using on() , to a containing element instead of directly on the element you're listening to. Relevant info:

If we were to click our newly added item, nothing would happen. This is because of the directly bound event handler that we attached previously. Direct events are only attached to elements at the time the .on() method is called. In this case, since our new anchor did not exist when .on() was called, it does not get the event handler.

Example:

$("#container-of-some-sort").on("click", ".saveButton", function(){ 
    saveForm(); 
});

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