简体   繁体   中英

jquery load function for a div not working

I just want to alert 'OK' when a div with id="Box" loads. But load function is not working. Here is my code in wordpress. I have included the jquery library and other jquery is working fine.

jQuery(function(){

jQuery( '#Box' ).load(function() {

alert('ok');
        });

    });

It does not work with DIV elements:

See: https://api.jquery.com/load-event/

"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."

Question:

I just want to alert 'OK' when a div with id="Box" loads. But load function is not working.


You are using .load() .

Answer A : This method will not work with a div .

Answer B : This method was deprecated in jQuery 1.8. Stop using it!

This method is a shortcut for .on( "load", handler ).

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.

https://api.jquery.com/load-event/


Possible solution :

Use the shorthand method .ajax() , .load() , .get to load content and trigger your stuff in the callback function or success handler.

.load() Load data from the server and place the returned HTML into the matched element.

http://api.jquery.com/load/

Example 1

Specify what to load in the first parameter and act in the callback function . The content of test.html is loaded, after that it's inserted into #box and the alert is fired.

$( "#result" ).load( "ajax/test.html", function() {
    alert( "Load was performed." );
});

Example 2

Ajax Example with load alert:

$.get("ajax/test.html", function(data) {
    $("#box").html(data);
    alert("Ok. Load.");
});

You are loading test.html the content is returned as data . It is assigned as new html content to the dom element #box . Then you fire the alert .

Example 3

The alternative is using the .ajax method and define a success handler:

function getData() {
    $.ajax({
        url : 'test.html',
        type: 'GET',
        success : alert('Ok.Loaded')
    });
}

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