2014-02-06 57 views
1

我在页面上有一些缩略图。当我点击其中的一个时,我想在Jquery对话框中查看原始照片。而且,我想根据照片宽度动态设置对话框的宽度。所以,我写了下面的脚本来完成它。但是,它看起来像我不能访问新添加到div的图像。以下是我写的功能:如何在使用jquery追加元素后调用函数?

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

它能够获取新添加的元素,但是由于两个原因,您的代码不会运行。

  1. 如果对话框被隐藏与显示:无的CSS,它或它的儿童的高度或宽度的任何计算将作为显示装置没有高度= 0,宽度= 0返回0。

  2. 图片需要时间加载。 Jo在将它添加到dom后不能计算它的高度。在这种情况下,它将始终使用父级的计算维度或您在CSS上定义的级别。

试试这个。

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. 在计算宽度之前,您的图像将准备就绪。

你也应该在对话框中给最小宽度和高度,直到图像加载它应该获得一定的宽度和高度。另外,您可以在加载图像之前显示一些加载图像。

+0

非常感谢。 – Newbie

0

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

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

function loaded(img){ 
    alert($(img).width()); 
} 
相关问题