javascript - 如何在使用 jquery append 元素后调用函数?

标签 javascript jquery dialog append

我在页面上有一些缩略图。当我单击其中一个时,我想在 Jquery 对话框中查看原始照片。而且,我想根据照片宽度动态设置对话框的宽度。因此,我编写了以下脚本来完成它。但是,看起来我无法访问新 append 到 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
} 

最佳答案

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

  1. 如果 dialogBox 使用 display:none css 隐藏,则对其或其子项的高度或宽度的任何计算都将返回 0,因为 display none 表示高度 =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. 您的图像将在计算其宽度之前准备就绪。

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

关于javascript - 如何在使用 jquery append 元素后调用函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21592978/

相关文章:

javascript - 从键盘输入时,每 n 个字符后加破折号

javascript - Bootstrap 3 Datepicker不显示日历

jQuery UI 日期选择器在对话框中自动打开

c++ - 重新编译前 Visual Studio 2010 文件修改警告对话框

javascript - 使用 makeChart() 创建图表后,无法添加其他图表

javascript - Joi 嵌套模式

jquery - 移动元素以重新聚焦

由 C# Photoshop CS5 Scripting 编写

javascript - 浏览器页面刷新后,Angular js 不会路由到默认页面

javascript - DOM 插入的简单 JavaScript 错误