【问题标题】:How to store data retrieved through AJAX for later use如何存储通过 AJAX 检索到的数据以供以后使用
【发布时间】:2012-01-29 04:01:57
【问题描述】:

我有一个应用程序可以打开一个带有多个图像缩略图的 div。单击图像时,将打开一个新的 div,该图像为全尺寸,并且该 div 应与图像具有相同的宽度和高度。

我从 php 文件中检索带有多个参数的对象,例如。 thumbWidth/thumbHeight 和宽度/高度。我需要做的是存储每个图像的宽度和高度,以便我可以打开一个正确大小的 div。最好的方法是什么?我想我可以将宽度和高度存储在一个多维数组中,但我想有更好的方法吗?

正如您在下面的代码中看到的那样,我尝试存储例如。变量“imgWidth”中的 this.width 并将其应用于事件,但每个图像都会获取最后检索到的宽度和高度,因此不起作用。

$.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();
    });
});

【问题讨论】:

    标签: jquery ajax json dom getjson


    【解决方案1】:

    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') + ")");  
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-01-28
      • 2021-11-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多