简体   繁体   中英

Using jquery.load and trying to avoid including the same code twice

I'm using JQuery.load() to pull the contents of a file into a webpage. The javascript to pull this off is in a separate .js file to keep things tidy.

/* Pulls in file contents */
    $(function() {
    $('.div').load('file.html');
});

However, when the file is pulled in the jquery animation I am using to crossfade images - the code for which is also in the .js file - doesn't work.

/* Crossfade code */
$(function(){
$(".appearing-image img").css("opacity",0).fadeTo(300, 0);
$(".appearing-image img").mouseover(function () {
        $(this).fadeTo(200, 1);
    });
$(".appearing-image img").mouseout(function () {
        $(this).fadeTo(200, 0);
    });
});

I found out that the only way to get it to work was to include it in the .load() code.

/* Pulls in file contents and executes animation */
$('.div').load('file.html',     $(function(){
            /* Crossfade images */
            $(".appearing-image img").css("opacity",0).fadeTo(300, 0);
            $(".appearing-image img").mouseover(function () {
            $(this).fadeTo(200, 1);
            });
            $(".appearing-image img").mouseout(function () {
            $(this).fadeTo(200, 0);
            });
        });
    });

That works.

However, elsewhere on the page other images won't crossfade unless the code is also included by itself, separate from the .load() which means I am now including the code twice.

Is there anyway to avoid this?

Use an external function, such as something like crossfade()

/* Crossfade code */
function crossfade(){
$(".appearing-image img").css("opacity",0).fadeTo(300, 0);
$(".appearing-image img").mouseover(function () {
        $(this).fadeTo(200, 1);
    });
$(".appearing-image img").mouseout(function () {
        $(this).fadeTo(200, 0);
    });
}

/* Pulls in file contents and executes animation */
$('.div').load('file.html', function(){
    /* Crossfade images */
    crossfade();
});

You may use

$(window).bind('setup', function() {
   //code
});

to load something before the document is ready

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