简体   繁体   中英

JQuery / Javascript function requies both $(document).ready and $(document).ajaxSucces

I have a JQuery / Javascript function that is to be used across my site for some basic UI functionality. However, many of the elements that this function effects, will be injected via Ajax, while others will be static html.

Currenty I've been able to make my scripts work for me by duplicating the function and applying both $(document).ready and $(document).ajaxSucces.

My question is: What is the appropriate accomplishing this?

This is my JS:

    $(document).ready(function () {
        $(".hidesfieldset:not(:first)").hide();
        $("fieldset").bind("focus click",function () {
            $(".hidesfieldset:not(:parent)").hide(800);
            $(".hidesfieldset", this).slideDown(800);

        });

    });

     $(document).ajaxSuccess(function () {
        $(".hidesfieldset:not(:first)").hide();
        $("fieldset").bind("focus click",function () {
            $(".hidesfieldset:not(:parent)").hide(800);
            $(".hidesfieldset", this).slideDown(800);

        });

    });

Because some of my forms are inject via ajax, the first function is not applied to them, so I also had to include the ajax Success.

Note*: I'm a complete newb when it comes to JS, this is my first time working with it, probably in a little over my head. So if you see other things in this that are wrong, feel free comment.

Thanks, Mark

When you are adding objects to the page asychronously via ajax and you want to hook up event handlers to some of those newly added objects, you have these options:

  1. You can use delegated event handling by assigning a delegated event handler to a static parent object that is present in the page at the time the page is originally loaded.

  2. You can add event handlers to the dynamically added objects in the success handler of the ajax call that added them after the objects have been added to the page.

  3. You can check for new objects in the page after all ajax calls (this is somewhat of a hack, but it sounds like what you're doing). You will have to be very careful to not add duplicate event handlers to objects that already existed before this ajax call.

If the structure of your page HTML and classes is designed for it, then delegated event handling is often the simplest way to handle this. Here are a few previous answers that describe how to use delegated event handling:

jQuery .live() vs .on() method for adding a click event after loading dynamic html

JQuery Event Handlers - What's the "Best" method

Does jQuery.on() work for elements that are added after the event handler is created?

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