[英]How can I call a function after appending an element using jquery?
我在页面上有一些缩略图。 当我单击其中一个时,我想在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
}
它能够获取新添加的元素,但是由于两个原因,您的代码将无法运行。
如果dialogBox用display:none css隐藏,则其或其子项的高度或宽度的任何计算都将返回0,因为display none表示height = 0,width = 0。
加载图像需要时间。 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
}
它将解决这两个问题。
它把它放到事件回调上,所以它总是在对话框open语句之后被调用。
在计算宽度之前,您的图像已准备就绪。
您还应该在对话框上提供最小宽度和高度,以便在加载图像之前,它应该获得一定的宽度和高度。 另外,您可以在加载图像之前显示一些加载图像。
您可以在图像上添加onload事件,例如
$('#image_frame').append('<img onload="loaded(this)" src="../IMAGE_PATH/'+$photo_name +'" />');
function loaded(img){
alert($(img).width());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.