0

我最近遇到了这样的问题,不知道如何解决。我有一个 HTML 图像表:

  1. 表格行数会根据用户输入动态变化,无需页面刷新
  2. 表中的每一行都包含数据库中的一个特殊图像
  3. 我想为显示的行加载图像(许多其他行被隐藏,所以我不想为它们加载图像)

我发现了一个如下片段:

var img = $("<img />").attr('src', 'http://somedomain.com/image.jpg')
    .load(function() {
        if (!this.complete || typeof this.naturalWidth == "undefined" || this.naturalWidth == 0) {
            alert('broken image!');
        } else {
            $("#something").append(img);
        }
    });

但问题是,在 .load 方法上,图像本身会忘记它应该放在哪里(因为我使用 for 循环在表格中逐行加载图像)

有没有人知道如何解决这个问题?

4

1 回答 1

0

您需要将图像与其行相关联。如果您在创建图像时手头有该行,则可以在对.load. 例如,如果在某个时候您有一个新行列表,您可以执行以下操作:

var loadImageForRow = function(row) { 
    var img = $("<img/>").attr('src', 'my-image-source.png')
        .load(function() { 
            if (!this.complete || typeof this.naturalWidth == 'undefined' || this.naturalWidth == 0) {
                // handle broken image
            } else {
                 row.find('.image-cell').append(img);
            }
        });
});

newRows.each(function() { loadImageForRow($(this)); } 

这使用row来自回调内部封闭闭包的参数。或者,您可以使用图像或行上的数据属性(例如data-row-index='17'img元素上放置类似的东西)或任何等效机制来关联两者。

于 2012-10-02T07:02:44.557 回答