1

我正在尝试动态创建一个表格用特定数量的单元格填充它,具体取决于视口的宽度。我还想确保它会在页面加载时调整屏幕的宽度(因此不仅仅是常规的屏幕尺寸)。

到目前为止,这是我尝试过的,此代码在window.onload函数内:

JavaScript

        var table = document.getElementById('instagram_table_body');

        /* Number of elements per row */
        var rowElems = Math.floor(screen.width / 152);

                    /* Number of rows */
        var rowCount = Math.ceil(data.length / rowElems);

        var globalCounter = 0;

        for (var i=0; i<rowCount; i++) {
            var tr = document.createElement('tr');

            for (var j = 0; j < rowElems; j++) {
                var td = document.createElement('td');
                var img = document.createElement('img');
                var a = document.createElement('a');

                a.href = data[globalCounter].images.standard_resolution.url;

                img.src = data[globalCounter].images.thumbnail.url;

                tr.appendChild(td.appendChild(a.appendChild(img)));

                globalCounter++;
            }
            table.appendChild(tr);
        }

问题是这段代码没有输出任何东西,实际上没有tr附加到表体中。我知道使用的数据在那里并且有效(它来自 AJAX 调用并在常规动态表中显示它可以正常工作。

问题似乎与子附加过程或当我将行附加到表的那一刻有关,我还不能完全发现它。

注意:我正在努力提高效率,这是 jQuery 不存在的主要原因。(它实际上只用于$.getand$.post方法)

JSFiddle

4

2 回答 2

2

If you have less than an even multiple of rowElems*rowCount items in your data list, then you will be overrunning the data array.

For example, let's say you have 7 items in your array but you can only fit six on the screen. You will loop over elements [0-5], append them to the table object, and then increase your row count. Then, you're looping over elements [6-11], but your array only contains 7 objects.

You should only see the last table row failing to display. If you have only one row in your data set, you'll see nothing at all in your table, since the call to table.appendChild(tr) will never be reached.

Also, Diodeus' comments wrt dom manipulation are good ones.

于 2013-07-15T20:49:43.467 回答
0

按照DiodeusKyleFransham的提示,我一直在寻找一种方法来防止最后一行崩溃,导致我进入Object.keys(data).length;.

我创建了一个变量来获取我的 JSON 对象的长度。然后,在我的for... in循环结束时,我只是检查我globalCounter是否等于我的对象的长度。如果是,我就跳出循环!

在我自己测试性能innerHTML之后,我也改变了,而不是方法。appendChild()

JavaScript

var table = document.getElementById('instagram_table_body');
var elemCount = Object.keys(data).length;
/* Number of elements per row */
var rowElems = Math.floor(screen.width / 152);

/* Number of rows */
var rowCount = Math.ceil(data.length / rowElems);

var globalCounter = 0;

for (var i = 0; i < rowCount; i++) {
    var tr = "<tr>";

    for (var j = 0; j < rowElems; j++) {
        var td = ('<td><a href="' + data[globalCounter].images.standard_resolution.url + '"><img src="' + data[globalCounter].images.thumbnail.url + '"/></a></td>');

        tr += td;

        globalCounter++;

        if (globalCounter == elemCount) break;
    }
    tr += "</tr>";
    table.innerHTML += (tr);
}
于 2013-07-16T12:56:38.990 回答