如何在使用jquery追加元素后调用函数?

时间:2014-02-06 02:40:32

标签: javascript jquery dialog append

我在页面上有一些缩略图。当我点击其中一个时,我想在Jquery对话框中查看原始照片。并且,我想根据照片宽度动态设置对话框的宽度。所以,我写了以下脚本来做到这一点。但是,看起来我无法访问新附加到div的图像。以下是我写的函数:

 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
} 

2 个答案:

答案 0 :(得分:2)

它能够获取新添加的元素,但是您的代码将无法运行,原因有两个。

  1. 如果使用display:none css隐藏了dialogBox,则其子项或其子项的高度或宽度的任何计算都将返回0,因为display none表示height = 0,width = 0.

  2. 图片需要一段时间才能加载。 Jo刚刚在dom上添加它后无法计算它的高度。在这种情况下,它将始终使用其父级或您在css上定义的内容进行计算维度。

  3. 试试这个。

     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
    
    }
    

    它将解决这个问题。

    1. 将其置于事件回调中,因此在对话框打开语句后将始终调用它。

    2. 在计算宽度之前,您的图像就已准备就绪。

    3. 您还应该在对话框中给出最小宽度和高度,因此在图像加载之前,它应该获得一些宽度和高度。另外,您可以在加载图像之前显示一些加载图像。

答案 1 :(得分:0)

您可以在图像上添加onload事件,例如

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

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