.load jquery function not working when using speci

2019-07-29 09:32发布

问题:

This line does not work

$('#bookcontainer').load( startSlide );

while this line does

$(window).load( startSlide );

#bookcontainer is a div containing four images.

Here's my whole code:

// JavaScript Document
$('#bookcontainer').load( startSlide );

var slide;

$('#slider').hover( 
function() {
        $('.arrow').show();
}, 
function() {
        $('.arrow').hide();
});

function startSlide() {
    $('.book').show();
    slide = setInterval(slideR, 5000);   
}


function slideR() {
    $('.book').first().css('left', '960px').appendTo('#bookcontainer').animate(
    {
        "left": "-=960px"
    }, {
        duration: 1000,
        easing: 'easeOutCubic'
    });

}


function slideL() {
    $('.book').last().animate(
    { "left":"+=960px" }, {
        duration: 1000,
        easing: 'easeOutCubic',
        complete: function() {
        $(this).prependTo('#bookcontainer').css('left', '0px');   
        }
    });

}


function right() {
    clearInterval(slide);
    slideR();
    startSlide();
};


function left() {
    clearInterval(slide);
    slideL();
    startSlide();
};

回答1:

The load event can only be handled on elements that are associated with a url. From the documentation:

The load event is sent to an element when it and all sub-elements have been completely loaded. This event can be sent to any element associated with a URL: images, scripts, frames, iframes, and the window object.

If you're waiting on all of your images to load, you could apply the event handler to those images individually.

Also: $(window).load(...) will not be fired until all elements on the page are fully loaded (including graphics), so it's not necessary to bind the event to a div to make sure child elements have loaded.

If you're making an AJAX request and attempting to detect when content has been loaded into that div, you should make startSlide the success callback to your AJAX request.



回答2:

You should use $('#bookcontainer').load('url', startSlide ); have a look at http://api.jquery.com/load/



回答3:

The div element does not trigger a load event.



标签: jquery load