开发者

How to load a table on a cell by cell basis

I have a simple table with a link and an image in a div in each cell. the simplified code is like:

<td>
    <a href="#"></a>
    <div>
        <img src="image01.jpg" />
    </div>
</td>

I pull the values for the link and the image from a the database and manually generate the table like:

cell = "<td>"
       + "<a href=\"#\"></a><div>"
       + "<img开发者_如何学Go src=\"" + imageName + "\" "
       + "\" alt=\"" + imageName + "\" /></div></td>";

When the user hovers the images, another image element is displayed to show a bigger version of the hovered image. This is done with javascript.

To be able to instantly respond to the hover, I actually load the bigger versions of the images in the table. I resize and crop them (hence the parent divs).

Since the table has around 40-100 cells, and the images vary between 180px to 800px width, I decided to load the empty table first, and then refresh the page with each cell content. This way the user will be able to interact with the loaded images, while the rest is still loading.

I think it is possible with an ajax loop that fires upon each page load with a counter set to the total number of cells. But I do not know how it can be done.

Is there a way to load the content of a cell, display it to the user and go on loadind the next cells?

Thank you for your time.


You can do it in javascript, with a help from jQuery to make the code cleaner.

The HTML you'll load have the image names on the data-src attribute, while the src is a blank file you should provide in your server (here, named blank.gif):

<td><img src='blank.gif' 
     style='width:100px;height:100px' 
     data-src='imagename.jpg' /></td>

This should be produced by the code:

cell = "<td><img src='blank.gif' style='width:" + imageWidth + 
        "px;" + imageHeight + "px' data-src='" + imageName + "' /></td>";

Providing the width and height is optional. If you can have then beforehand, the effect will be nicer. If you can't, the table will take shape only when the images are loading.

Finally, to load the contents, use the following script somewhere in your HTML:

<script>
$(function() {
    $("img").each(function() {
        var src=$(this).data("src"); //retrieve the data-src attribute
        if (src) $(this).attr("src", src); // if present, load the image
    });
})
</script>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜