用香草JS和循环画一张桌子 [英] Drawing a table with vanilla JS and loops

查看:40
本文介绍了用香草JS和循环画一张桌子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做一个练习(从Beginning Javascript开始),以更好地理解DOM操作.尝试仅使用JS以DRY方法重新创建下表(教科书解决方案是此处):

I am doing an exercise (from Beginning Javascript) to better understand DOM manipulation. Attempting to recreate the following table in a DRY method using only JS (the textbook solution is here):

<table>
    <tr>
        <td>Car</td>
        <td>Top Speed</td>
        <td>Price</td>
    </tr>
    <tr>
        <td>Chevrolet</td>
        <td>120mph</td>
        <td>$10,000</td>
   </tr>
   <tr>
       <td>Pontiac</td>
       <td>140mph</td>
       <td>$20,000</td>
   </tr>
</table>

我尝试过此方法,但不确定如何循环创建变量而不会引发错误:

I tried this but unsure how you can loop variable creation without throwing an error:

var array = [['Car', 'Top Speed', 'Price'],['Chevrolet', '120mph', '$10,000'], ['Pontiac', '140pmh', '$20,000']] // Creating a data array which a loop will source from

    var table = document.createElement('table');
    document.body.appendChild(table); // Drew the main table node on the document

    for (var i = 0; i<3; i++) { 
        var tr[i] = document.createElement('tr'); //Create 3 <tr> elements assigned to a unique variable BUT need a working alternative for 'tr[i]'
        table.appendChild(tr[i]); // Append to <table> node

        for (var j = 0; j<3; j++) {

            var tdText = document.createTextNode(array[i][j]); // Extract data from array to a placeholder variable
            tr[i].appendChild(tdText); // Take string from placeholder variable and append it to <tr> node
        }
    }

推荐答案

请使用 tr 代替 tr [i] .会起作用的

Please use tr instead of tr[i]. It will work

var array = [['Car', 'Top Speed', 'Price'],['Chevrolet', '120mph', '$10,000'], ['Pontiac', '140pmh', '$20,000']] // Creating a data array which a loop will source from

    var table = document.createElement('table');
    document.body.appendChild(table); // Drew the main table node on the document

    for (var i = 0; i<3; i++) { 
        var tr = document.createElement('tr'); //Create 3 <tr> elements assigned to a unique variable BUT need a working alternative for 'tr[i]'
        table.appendChild(tr); // Append to <table> node

        for (var j = 0; j<3; j++) {
            var tdElement = document.createElement('td');
            tdElement.innerHTML = array[i][j];
            tr.appendChild(tdElement); // Take string from placeholder variable and append it to <tr> node
        }
    }

这篇关于用香草JS和循环画一张桌子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆