简体   繁体   中英

Targetting elements loaded with jquery load()

I am doing a website where all internal links make the current page fade out and the new contents fade in. I do that with jquery load(). The loading and fading part works fine like this:

    var $mainContent = $("#ajaxcontainer"),
        $internalLinks = $(".internal"),
        URL = '',
        $ajaxSpinner = $("#loader"),
        $el;

    $internalLinks.each(function() {
        $(this).attr("href", "#" + this.pathname);
        }).on('click', function() {

            $el = $(this);

            URL = $el.attr("href").substring(1);
            URL = URL + " #container";

            $mainContent.fadeOut(500, function() {

                $ajaxSpinner.fadeIn();
                $mainContent.load(URL, function() {
                    $ajaxSpinner.fadeOut( function() {
                        $mainContent.fadeIn(1000);
                    });         
                });

            });


        });

As you can see, I am targetting all internal links by a class I've given them (.internal). My problem is that once content gets loaded with ajax, I am not able to target this new content with my jquery, and so the $internalLinks.each() and so on gets broken, meaning that the site just reverts back to the default link behavior.

Another thing which is related to this, is that I want to be able to target this newly loaded content with the jquery.masonry plugin. That also isn't possible the way I'm doing things now. Thank you very much.

When you update the page, the old .internal links are removed, so the event handler attached to them won't work. Change your code to use event delegation:

$('.internal').each(function() {
    $(this).attr("href", "#" + this.pathname);
}); 

$(document).on('click', '.internal', function() {

        $el = $(this);

        URL = $el.attr("href").substring(1);
        URL = URL + " #container";

        $mainContent.fadeOut(500, function() {

            $ajaxSpinner.fadeIn();
            $mainContent.load(URL, function() {
                $ajaxSpinner.fadeOut( function() {
                    $mainContent.fadeIn(1000);
                });
                $('.internal').each(function() {
                    $(this).attr("href", "#" + this.pathname);
                });        
            });

        });
});

As you see, I refresh the attribute href of each link after a refresh, too.

** EDITED ** I was missing changing the href attribute the first time. Now it should work!

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