简体   繁体   中英

How do I load content in specific DIV after the page loads?

I am wondering how I would load another PHP page into a DIV container after the parent page has loaded. I need to design facebook/twitter share links that will show people my page with certain content loaded into a DIV.

I have a function working for clicking links, but I need it to work on page load rather than click (#results is the ID of the DIV I need content loaded into):

$(".Display a").click(function() {
  $.ajax({
   url: $(this).attr("href"),
   success: function(msg){
     $("#results").html(msg);
   }
 });
 return false;
});

You can use jQuery's .ready() event on the document:

$(document).ready(function () {
    // Whatever you want to run
});

This will run as soon as the DOM is ready.

If you need your javascript to run after everything is loaded (including images) than use the .load() event instead:

$(window).load(function () {
    // Whatever you want to run
});

I'd suggest keeping your original click-handler, and triggering it with:

$(".Display a").click(function() {
  $.ajax({
   url: $(this).attr("href"),
   success: function(msg){
     $("#results").html(msg);
   }
 });
 return false;
});

$(document).ready(
    function(){
        $('.Display a').trigger('click');
    });

Have you tried just using the $.ajax() outside of the click event?

Instead of --

$(".Display a").click(function() {
    $.ajax({
      url: $(this).attr("href"),
      success: function(msg){
        $("#results").html(msg);
      }
    });
  return false;
});

Try this --

$(document).ready(function () {
      $.ajax({
        url: $(this).attr("href"),
        success: function(msg){
                 $("#results").html(msg);
        }
       }); 
});
$(function(){ //jQuery dom ready event

    $(".Display a").click(function() {
        ///you code
    }).click(); //trigger it at the page load

});

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