简体   繁体   English

使用for循环从数组中获取数据以填充表

[英]Grabbing data from an array using for loop to populate a table

Problem 问题

I'm trying to iterate over an array of objects using a for loop , but instead of getting all the items in the array that I actually see when I console.log(arr[i].Sand) I get the same number eleven times in my HTML. 我试图使用for loop遍历对象数组,但是没有获得当我console.log(arr[i].Sand)时实际看到的数组中的所有项目,我得到了11次相同的数字在我的HTML中。

script.js script.js

$(function(){

    $.ajax({
        url: "https://sheetsu.com/apis/fef35fba",
        method: "GET",
        dataType: "json",
    }).then(function(spreadsheet){

        // Array of objects
        var arr = spreadsheet.result;

        for (i = 1; i < arr.length; i++) {
            console.log(arr[i].Sand); // Just the volume of sand in tonnes

            var sand = arr[i].Sand // Volume of Sand in tonnes
            var salt = arr[i].Salt // Volume of Salt in tonnes
            var snow = arr[i].Snow // Snow Removal total in dollars

            // Changes the numbers in the table
            $(".sand").html(sand);
        }
    })
});

spreadsheet.result 电子表格。结果

在此处输入图片说明

index.html index.html

<table>
    <thead>
        <tr>
            <th class="year"></th>
            <th>
                <img src="img/sand-2.png" alt="" class="icons">
                <p>Volume of Sand</p>
                <p class="paren">(in tonnes)</p>
            </th>

            <th>
                <img src="img/salt-3.png" alt="" class="icons">
                <p>Volume of Salt</p>
                <p class="paren">(in tonnes)</p>
            </th>

            <th>
                <img src="img/snow-3.png" alt="" class="icons">
                <p>Snow Removal</p>
                <p class="paren">(total in dollars)</p>
            </th>
        </tr>
    </thead>

    <tbody>
        <tr>
            <td class="year">2016</th>
            <td class="sand">-<span class="asterisk">*</span></td>
            <td class="salt">-<span class="asterisk">*</span></td>
            <td class="snow">-<span class="asterisk">*</span></td>
        </tr>

        <tr>
            <td class="year">2015</th>
            <td class="sand">-</td>
            <td class="salt">-</td>
            <td class="snow">-</td>
        </tr>

        <tr>
            <td class="year">2014</th>
            <td class="sand">-</td>
            <td class="salt">-</td>
            <td class="snow">-</td>
        </tr>

        <tr>
            <td class="year">2013</th>
            <td class="sand">-</td>
            <td class="salt">-</td>
            <td class="snow">-</td>
        </tr>

        <tr>
            <td class="year">2012</th>
            <td class="sand">-</td>
            <td class="salt">-</td>
            <td class="snow">-</td>
        </tr>

        <tr>
            <td class="year">2011</th>
            <td class="sand">-</td>
            <td class="salt">-</td>
            <td class="snow">-</td>
        </tr>

        <tr>
            <td class="year">2010</th>
            <td class="sand">-</td>
            <td class="salt">-</td>
            <td class="snow">-</td>
        </tr>

        <tr>
            <td class="year">2009</th>
            <td class="sand">-</td>
            <td class="salt">-</td>
            <td class="snow">-</td>
        </tr>

        <tr>
            <td class="year">2008</th>
            <td class="sand">-</td>
            <td class="salt">-</td>
            <td class="snow">-</td>
        </tr>

        <tr>
            <td class="year">2007</th>
            <td class="sand">-</td>
            <td class="salt">-</td>
            <td class="snow">-</td>
        </tr>

        <tr class="last">
            <td class="year">2006</th>
            <td class="sand">-</td>
            <td class="salt">-</td>
            <td class="snow">-</td>
        </tr>
    </tbody>
</table>

while I was generating the code to answer this, someone changed your ajax call. 当我生成代码来回答这个问题时,有人更改了您的ajax调用。

Here's the code reworked so it should help. 这是重新编写的代码,因此应该会有所帮助。

    $(function(){

    $.ajax({
        url: "https://sheetsu.com/apis/fef35fba",
        method: "GET",
        dataType: "json",
    }).then(function(spreadsheet){

        // Array of objects
        var arr = spreadsheet.result;

        for (i =0; i < arr.length; i++) {
            console.log(arr[i].Sand); // Just the volume of sand in tonnes

             sand = arr[i].Sand // Volume of Sand in tonnes
             salt = arr[i].Salt // Volume of Salt in tonnes
             snow = arr[i].Snow // Snow Removal total in dollars
             year = arr[i].Year; //We need the year to find the right row

            // Changes the numbers in the table
            $("tr").each(function(){
                //We need to find the correct TR object.
     //Remove Any spacing outside the html to make sure we don't get anything extra. 
     // We need to locate the ROW that has the right year so we can populate ONLY it's columns. an id or class based off year would have made this easier and less resource expensive.

              if($(this).find(".year").html().trim() == year){ 

                $(this).find(".sand").html(sand);
                $(this).find(".salt").html(salt);
                $(this).find(".snow").html(snow);
              } 
            });
        }
    })
});

Here is a JSFiddle to show it: https://jsfiddle.net/g6vn4Lf6/ 这是显示它的JSFiddle: https ://jsfiddle.net/g6vn4Lf6/

This line: 这行:

$(".sand").html(sand);

Finds all elements with class="sand" and then sets the inner html of all of them to the value of sand . 查找所有带有class="sand"元素,然后将所有元素的内部html设置为sand的值。 Instead you need to label each row of the table with html (eg <tr class="year-2015"> ), then you can select the right td element by using something like $(".year-2015 .sand") . 相反,您需要用html标记表的每一行(例如<tr class="year-2015"> ),然后可以使用$(".year-2015 .sand")类的东西来选择正确的td元素。

First, you should change the key of the year in your json response to "year" instead of "" 首先,您应该将json响应中的年份键更改为"year"而不是""

Then you should associate that year with the tr's in some way, such as <tr year='2016'> 然后,您应该以某种方式将该年份与tr关联,例如<tr year='2016'>

Then in your for loop you can select just the .sand element that is a child of the correct tr. 然后在for循环中,您可以仅选择.sand元素,它是正确tr的子元素。 $("tr[year='" + arr[i].year + "'] .sand").html(sand)

perhaps you should dynamically add a row for each of the results you receive from your ajax call like shown below: 也许您应该为从ajax调用中收到的每个结果动态添加一行,如下所示:

 $(document).ready(function() { var arrayResults = [ { Year: '2016', Sand: '123', Salt: '234', Snow: '345' }, { Year: '2015', Sand: '222', Salt: '333', Snow: '444' }, { Year: '2014', Sand: '555', Salt: '111', Snow: '888' }, { Year: '2013', Sand: '121', Salt: '232', Snow: '343' }, { Year: '2012', Sand: '454', Salt: '565', Snow: '676' } ]; for(var i = 0; i < arrayResults.length; i++) { var newRow = '<tr>'; newRow += '<td class="year">' + arrayResults[i].Year + '</td>'; newRow += '<td class="sand">' + arrayResults[i].Sand + '</td>'; newRow += '<td class="salt">' + arrayResults[i].Salt + '</td>'; newRow += '<td class="snow">' + arrayResults[i].Snow + '</td>'; newRow += '</tr>'; $('tbody').append(newRow); } }); 
 th, td { border: 1px solid black; padding: 5px; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table> <thead> <tr><th>year</th><th>sand</th><th>salt</th><th>snow</th></tr> </thead> <tbody> </tbody> </table> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM