简体   繁体   中英

How can I call a function after appending an element using jquery?

I have some thumbnails on the page. When I click on one of those, I would like to view the original photo in a Jquery dialog. And, I would like to set the width of dialog box dynamically based on the photo width. So, I have written the following scripts to do it. However, It looks like that I can't access the image which is newly appended to the div. Below is the function I wrote:

 function showOrignalPhoto($photo_name){
     $('#image_frame img').remove(); //remove the previous image

     $('#image_frame').append('<img src="../IMAGE_PATH/'+$photo_name +'" />'); //append new image

     $width = $('#image_frame img').width(); //get width of the new image
     alert($width); //return 0!! 

     $( "#dialog" ).dialog( "option", "width", $width); //set the width of the dialog box

     $( "#dialog" ).dialog( "open" ); //open the dialog
} 

It is able to get the newly added element however your code will not run for two reasons.

  1. If dialogBox is hidden with display:none css , any calculation of its or its children's height or width will return 0 as display none means height =0 , width = 0 .

  2. Image takes time to load . Jo just after adding it on dom you can't calculate its height. In that case it will always calculative dimension using its parent or what you have defined on css.

Try this.

 function showOrignalPhoto($photo_name){
     $('#image_frame img').remove(); //remove the previous image

     //show some loading image before image is loaded.

      var img=$('<img class="thumbnail" src="../IMAGE_PATH/'+$photo_name +'" />');
      img.on('load',function(){
            //hide loading image after image is loaded.
            var width = this.width;
            console.log(width);
            $( "#dialog" ).dialog( "option", "width", width); //set the width of the dialog box
        });

      $( "#dialog" ).dialog( "open" ); //open the dialog

}

It will take care of both the problem.

  1. Its putting it on event callback so it will always be called after dialog open statement .

  2. You image will be ready before calculating its width.

You also should give minimum width and height on dialog box so until image is loaded it should gain some width and height. Plus you can show some loading image before image is loaded.

you can add onload event on image, eg

$('#image_frame').append('<img onload="loaded(this)" src="../IMAGE_PATH/'+$photo_name +'" />');

function loaded(img){
  alert($(img).width());
}

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