使用数组在 Javascript 中创建垂直动态 table

Creating a vertical, dynamic table in Javascript with an array

如果您只想阅读问题,请直接跳到底部。最上面的只是上下文。不重要但可能有帮助。

在 html 中处理 table 时,我意识到了一些事情。代码很糟糕,重复且浪费。可能因为我们一直在手动添加数组。

<!-- 
<table border="4px" >
            <caption>
            Pet Table
            </caption>
            <tr> // Images
                <td>
                    <script>
                    display(bat)
                    </script>;
                </td>
                <td>
                    <script>
                    display(goat)
                    </script>               
                </td>
                <td>
                    <script>
                    display(butterfly)
                    </script>   
                </td>
                <td>
                    <script>
                    display(buzzard)
                    </script>   
                </td>
                <td>
                    <script>
                    display(breezie)
                    </script>   
                </td>
                <td>
                    <script>
                    display(turtle)
                    </script>   
                </td>
            </tr >
            <tr> // Names
                <td>
                    name
                </td>
                <td>
                    name
                </td>
                <td>
                    name
                </td>
                <td>
                    name
                </td>
                <td>
                    name
                </td>
                <td>
                    name
                </td>               
            </tr>
            <tr> //Desc
                <td>
                    desc
                </td>
                <td>
                    desc
                </td>
                <td>
                    desc
                </td>
                <td>
                    desc
                </td>
                <td>
                    desc
                </td>
                <td>
                    desc
                </td>               
            </tr>
            <tr> //Food
                <td>
                    food
                </td>
                <td>
                    food
                </td>
                <td>
                    food
                </td>
                <td>
                    food
                </td>
                <td>
                    food
                </td>
                <td>
                    food
                </td>               
            </tr>
            <tr> //button
                <td>
                    button
                </td>
                <td>
                    button
                </td>
                <td>
                    button
                </td>
                <td>
                    button
                </td>
                <td>
                    button
                </td>
                <td>
                    button
                </td>               

        </table>
 -->        

这让我花了整个上午的时间进行理论化和实验,而不是从 javaScript 动态创建 table。

这是我想出的代码。

在JavaScript中(*编辑添加的宠物阵列)

function pet(species, name, colour, size, food, limb, img) {
    this.species = species; //property of a pet
    this.name = name; //property of a pet
    this.colour = colour; //property of a pet
    this.size = size; //property of a pet
    this.food = food; //property of a pet
    this.limb = limb; //property of a pet
    this.img = img; //property of a pet         
    this.move = move; //a function of a pet defined to the pet      

    var bat = new pet("fruit bat", "bats", "grey", "small", "apples", "wings", "1", move);
    var goat = new pet("goat", "bastard", "off white", "goat-sized", "clothing", "hooves", "2", move);
    var butterfly = new pet("butterfly", "flutterby", "rainbow", "petite", "nectar", "wings", "3", move);
    var buzzard = new pet("buzzard", "Buzz", "molted black and white", "bigish", "carrion", "wings", "4", move);
    var breezie = new pet("pixie", "petty", "blue", "tiny", "souls", "wings", "5", move);
    var turtle = new pet("tortoise", "Tank", "Green", "smoothbacked", "lettuce", "legs", "6", move);

    var len = pet.length;

    function buildTable() {
        document.getElementById("work");
        //i is a counter, f is a flag   
        var f = 0;
        while (f = 0) {
            document.write("<table border='4px'>" + "</br>");
            document.write("<caption>Pets Avaliable</caption>" + "</br>");
            document.write("<tr>" + "</br>");
            for (i = 0; i <= len; i++) {
                document.write("<td>" + imgArray[i].outerHTML + "</td>" + "</br>");
            }
            document.write("</tr>" + "</br>");
            document.write("<tr>" + "</br>");
            for (i = 0; i <= len; i++) {
                document.write("<td>" + pet[i].species + "</td> " + "</br>");
            }
            document.write("</tr>" + "</br>");
            document.write("<tr>" + "</br>");
            for (i = 0; i <= len; i++) {
                document.write("<td>" + pet[i].name + "</td>" + "</br>");
            }
            document.write("</tr>" + "</br>");
            document.write("<tr>" + "</br>");
            for (i = 0; i <= len; i++) {
                document.write("<td>" + pet[i].colour + "</td> " + "</br>");
            }
            document.write("</tr>" + "</br>");
            document.write("<tr>" + "</br>");
            for (i = 0; i <= len; i++) {
                document.write("<td>" + pet[i].size + "</td>" + "</br>");
            }
            document.write("</tr>" + "</br>");
            document.write("<tr>" + "</br>");
            for (i = 0; i <= len; i++) {
                document.write("<td>" + pet[i].food + "</td>" + "</br>");
            }
            document.write("</tr>" + "</br>");
            document.write("</table>" + "</br>");
            f = 1;
        }

    }
    document.getElementById("please");

HTML

<button id="please" onclick="buildTable(pet)"> Work you blighter </button>
<p id="work"></p>

我只是无法让它工作。控制台没有显示任何错误,但按钮没有提供任何结果。经过长时间的挖掘,我确实设法找到了一个有效的按钮。 (我将 .innerHTML = "The button is working" 添加到 document.getElementById("work") 以对其进行测试。)所以按钮没问题。因此问题一定出在函数本身对吧?该死的。我知道这是错误的,明天我会使用与这些帖子类似的代码再试一次 Dynamically creating a table in javascript /
http://jsfiddle.net/ahEkH/1/Create vertical column table based on Array of Objects 我不介意努力寻找答案,也不介意反复试验,但让我感到不安的是我无法弄清楚问题出在哪里。很高兴了解代码是如何工作的,但我也想知道为什么它会这样工作。

问题

  1. 为什么控制台和调试器都找不到任何错误,而页面却明显不工作。

  2. 以后遇到这类问题怎么标注?错在哪里?按钮?功能?两个都?两者都不?我自己?

  3. 我打算将 table 设为垂直列格式而不是水平列。这样做会有问题吗? (我在想更多的 for 循环应该可以毫不费力地解决问题)

  4. 我想使用预先构建的数组作为数据源(例如 pet[i].size 但这样做是否可行,或者是否更好地取消 -assemble在函数中将数组转化为变量?

  5. 如果我确实需要为所有数据创建变量,如果它在循环之一内,我是否能够回收或重用变量?

  6. http://jsfiddle.net/ahEkH/1/ 中,为什么 "tbdy" 是选项卡的子项或者 appendChild 用于将“tbdy" 分配给 tab

我现在知道如何着手修复动态 table 但我不知道一开始具体出了什么问题。请与我们分享您的知识。

您的代码中有一些内容。

  1. while(f=0){ 将始终评估为 0,因此为 false。您可能想要 while(f === 0) {(是的,三重 ===)。这导致了 "I don't see anything in the console" 问题,因为代码实际上(如您所怀疑的那样)工作,尽管不是您预期的那样。
  2. 你的每个循环都有 for(i = 0; i <= len; i++),其中 var len = pet.length; 你会得到一个超出范围的索引,你会想要更改为 for(i = 0; i < len; i++).

最后:

  1. 您可能不想使用 document.write。第一个 document.write 调用将清除文档并将其替换为您的 table。你最好让 document.createElement 和朋友一起做 DOM 操作(根据你发布的 jsfiddles)。如果你走这条路,你最好使用像 jQuery 这样的库,在那里你可能会得到这样的东西:

//
// Dummy data to make the sample work.
//
var imgArray = [
 {outerHTML: '1.jpg'}
, {outerHTML: '2.jpg'}
, {outerHTML: '3.jpg'}
, {outerHTML: '4.jpg'}
];

var pet = [
 {species: 'species1', name: 'name1', colour: 'colour1', size: 'size1', food: 'food1'}
, {species: 'species2', name: 'name2', colour: 'colour2', size: 'size2', food: 'food2'}
, {species: 'species3', name: 'name3', colour: 'colour3', size: 'size3', food: 'food3'}
, {species: 'species4', name: 'name4', colour: 'colour4', size: 'size4', food: 'food4'}
];

var attributes = $.map(pet[0], function(n, v) { return v; });

function generateTable(id) {
    var $table = $(id);
    var $tbody = $('<tbody></tbody>');
        
    $table.append($tbody);
        
    // the images
    var $tr = $('<tr />');
    $.each(imgArray, function (ignored, image) {
        $tr.append($('<td />').html(image.outerHTML));
    });
    $tbody.append($tr);
        
    $.each(attributes, function (ignored, attribute) {
        $tr = $('<tr />');
        $.each(pet, function (i, p) {
            // i == index, p == pet[i]
            $tr.append($('<td />').text(p[attribute]));
        });
        $tbody.append($tr);
    });
}

$(function () {
    $('#generateTable').click(function () {
        generateTable('#tableHere');
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button id="generateTable">Generate table</button>
<div id="tableHere"></div>

希望对您有所帮助。

Why can't the console and debugger find any errors yet the page is obviously not working.

代码中没有错误,只是没有实现您希望它执行的操作。

How would I label these kinds of problems in the future?What was at fault? The button? The function? Both? Neither? Myself?

有一些严重错误,很难指出一个决定。

I'm planning to make the table in a vertical column format instead of horizontal. Would this be problematic to do? (I'm thinking a few more for loops should do the trick without a fuss)

水平放置可能更容易。

I'd like to use a pre-constructed array as a source for data(e.g pet[i].size but would this work or would it be better to dis-assemble the array into variables in the function?

如果您要多次使用它,最好为 pet[i] 创建一个变量。如果您的意思是为尺寸、名称等制作单独的 tables - 不,没有必要。

if I do need to make variables for all the data would I be able to recycle or reuse a variable if it's inside one of the loops?

我不确定你的意思,但答案可能是肯定的。在 javascript 中,变量是函数的局部变量,一个函数内的所有循环、ifs 等都使用相同的变量。

In http://jsfiddle.net/ahEkH/1/ why is "tbdy" a child of tab or is appendChild used to assign "tbdy" to tab?

tbdy 是 table 元素 tab 的子元素,也就是说它在里面。

好的,现在您的代码有问题:

  1. while 中的代码永远不会执行。您的条件是赋值 f=0 而不是相等检查 f==0(或更好的 f===0)。 f=0 的值为 0,因此它是假的。而且,如果您希望它只执行一次,则根本不需要循环。
  2. document.write 在从 onclick 调用时不会正常工作。 document.write<script> 标记中直接调用时几乎完全有意义,一般应避免使用。
  3. 您对 document.getElementById 的调用只是 return 然后被遗忘的对象 - 它们没有任何效果。
  4. 你用参数pet调用buildTable,但是buildTable不接受任何参数(现在这不是什么大问题,因为pet似乎是全局的变量,但它可能会产生误导)。
  5. 您没有将 i 声明为局部变量,因此它是全局变量。它会工作,但非常容易出错。
  6. <br> 标签放在 <table> 中没有任何意义而且是不正确的,</br>(如您所写)isn't even legal tag。 你可能想把换行符 (\n) 放在那里,但这不是必需的,你不必分隔 html 标签。
  7. 您的代码非常重复,有很多几乎相同的 for 循环。
  8. 缩进你的代码,这样会更好读。

使用类似于您的方法的可能解决方案(从字符串中逐个构建 html):

(使用前(不推荐),仔细阅读以下注意事项)

var pet = [
    {
        species: 'species1',
        name: 'name1',
        colour: 'colour1',
        size: 'size1',
    },
    {
        species: 'species2',
        name: 'name2',
        colour: 'colour2',
        size: 'size2',
    },
];
    
function makeTr(pet, attrName) {
    var html = '',
        i;
    
    html += "<tr>";
    for (i = 0; i < pet.length; ++i) {
        html += "<td>" + pet[i][attrName] + "</td>";
    }
    html += "</tr>";
    return html;
}

function buildTable(pet) {
    var html='';
    
    html += "<table border='4px'>";
    html += "<caption>Pets Avaliable</caption>";
    
    html += makeTr(pet, "species");
    html += makeTr(pet, "name");
    html += makeTr(pet, "colour");
    html += makeTr(pet, "size");
    
    html += "</table>"

    document.getElementById("work").innerHTML = html;
}

(jsfiddle)

请注意,这远非最佳解决方案,请手动放置 html 原则上可能被认为是坏的(尽管它可能会更快并且 在某些情况下可能是合理的)。一般来说,创建 html 标签 document.createElement 似乎是一种更简洁、更不容易出错的方法。 具体来说,上面的代码可能会受到 XSS 攻击,因为放入 html 的值没有经过清理。 Paul 的解决方案不受此问题的影响 - 注意使用 text() 方法,它转义了 html 代码。