2011-12-28 82 views
1

我有一個應用程序,打開一個div與幾個縮略圖的圖像。當點擊一個圖像時,一個新的div將打開全尺寸的圖像,div的寬度和高度應與圖像相同。如何存儲通過AJAX檢索數據供以後使用

從php文件我回顧了幾個參數的對象,例如。 thumbWidth/thumbHeight和寬度/高度。我需要做的是存儲每個圖像的寬度和高度,以便我可以打開正確大小的div。什麼是最好的方式來做到這一點?我想我可以將寬度和高度存儲在多維數組中,但我想有更好的方法嗎?

正如你可以在下面的代碼中看到的,我嘗試存儲例如。 this.width在變量'imgWidth'中並將其應用於事件,但每個圖像都會獲取最後一次檢索的寬度和高度,因此不起作用。

$.getJSON('...getJSONThumbs.php', function(json) { 
    $.each(json, function() { 

     if (this.thumbWidth > maxWidth){ 
      maxWidth = this.thumbWidth; 
     } 

     if (this.thumbHeight > maxHeight){ 
      maxHeight = this.thumbHeight; 
     } 

     var box = $('<div/>', { 
      'class': 'imgDiv', 
      'width': maxWidth, 
      'height': maxHeight, 
     }).appendTo('.imageArea:last'); 

     var a = $('<a/>', { 
      'href': '#', 
     }).appendTo(box) 

     var img = $('<img/>', { 
      'src': 'pics/' + this.fileName, 
      'width': this.thumbWidth, 
      'height': this.thumbHeight, 
     }).appendTo(a); 

     imgWidth = this.width; 
     imgHeight = this.height; 

     box.click(function(event) { 
      event.preventDefault(); 
      console(imgWidth + " " + imgHeight); // always the last images width and height 
      $('#desktop').css("background-image", "url(" + img.attr('src') + ")"); 
     }); 

     jQuery(loaderImage).hide(); 
    }); 
}); 

回答

2

jQuery提供了一種通過.data()方法將數據關聯到元素的方法。

當你綁定box對象上的處理程序,我想補充的數據在那裏,就像這樣:

box.data('imgWidth', this.width); 

您檢索與值:

var width = box.data('imgWidth'); 

應用到你的代碼,我可能這樣做:

var params = this; // for the sake of the example (the current json object) 

var box = $('<div/>', { 
    'class': 'imgDiv', 
    'width': maxWidth, 
    'height': maxHeight, 
}) 
.data('imgSize', params); // save the data to the element 
.appendTo('.imageArea:last'); 

... 

box.click(function(event) { 
    event.preventDefault(); 

    // get back the saved data 
    var savedParams = $(this).data('imgSize'); 
    console(savedParams.width + " " + savedParams.height); 

    $('#desktop').css("background-image", "url(" + img.attr('src') + ")"); 
}); 
+0

工程就像一個魅力,謝謝! – holyredbeard 2011-12-28 13:19:27

相關問題