簡體   English   中英

使用jQuery追加元素后如何調用函數?

[英]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
} 

它能夠獲取新添加的元素,但是由於兩個原因,您的代碼將無法運行。

  1. 如果dialogBox用display:none css隱藏,則其或其子項的高度或寬度的任何計算都將返回0,因為display none表示height = 0,width = 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. 它把它放到事件回調上,所以它總是在對話框open語句之后被調用。

  2. 在計算寬度之前,您的圖像已准備就緒。

您還應該在對話框上提供最小寬度和高度,以便在加載圖像之前,它應該獲得一定的寬度和高度。 另外,您可以在加載圖像之前顯示一些加載圖像。

您可以在圖像上添加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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM