如何使用for循环简化我的JavaScript函数?

时间:2014-02-11 22:34:04

标签: javascript

我编写了以下JavaScript函数来从Yahoo Finance检索股票信息。我想用for循环简化代码,以避免重复这三行:

var cell = row.insertCell(0);
var newText = document.createTextNode(data.query.results.quote.Symbol);
cell.appendChild(newText);

我试图用这些线代替上面的内容,但无济于事。你有什么建议吗?

var dataElement=[data.query.results.quote.Symbol,
    data.query.results.quote.StockExchange,
    data.query.results.quote.Ask,
    data.query.results.quote.Bid,
    data.query.results.quote.PERatio,
    data.query.results.quote.DividendYield,
    data.query.results.quote.PriceBook];

for (i = 0; i < dataElement.length; i++) {  
    var cell = row.insertCell(i);
    var newText =document.createTextNode(dataElement[i]);
    cell.appendChild(newText);
}

这是完整的HTML / js代码,没有for循环:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="en-GB" xml:lang="en-GB">

<head>
    <meta charset="UTF-8" /> 
    <title>
        Retrieve stock data from Yahoo Finance
    </title>
    <script type="text/javascript" src="jQuery.js"></script>
</head>

<body>
    <input type="text" id="inputSymbol" />

    <table id='stockDataTable'>
        <thead>
            <tr>
                <td>Symbol</td>
                <td>Stock Exchange</td>
                <td>Ask</td>
                <td>Bid</td>
                <td>PE Ratio</td>
                <td>Dividend Yield</td>
                <td>Price-to-Book Ratio</td>
            </tr>           
        </thead>
        <tbody>
        </tbody>
        <tfoot>
            <tr>
                <td colspan="3" id='status'></td>
            </tr>
        </tfoot>
    </table>

    <button type="submit" onClick="addTicker();">Add Ticker to Table</button>
    <button type="submit" onClick="deleteTicker();">Remove Ticker from Table</button>

    <script type="text/javascript">
        function addTicker() {
            var url = "http://query.yahooapis.com/v1/public/yql";
            var symbol = $("#inputSymbol").val();
            var data = encodeURIComponent("select * from yahoo.finance.quotes where symbol in ('" + symbol + "')");

            var table = document.getElementById("stockDataTable").getElementsByTagName('tbody')[0];
            var row = table.insertRow(table.rows.length);

            $.getJSON(url, 'q=' + data + "&format=json&diagnostics=true&env=http://datatables.org/alltables.env")
                .done(function (data) {

                    var cell = row.insertCell(0);
                    var newText = document.createTextNode(data.query.results.quote.Symbol);
                    cell.appendChild(newText);

                    var cell = row.insertCell(1);
                    var newText = document.createTextNode(data.query.results.quote.StockExchange);
                    cell.appendChild(newText);

                    var cell = row.insertCell(2);
                    var newText = document.createTextNode(data.query.results.quote.Ask);
                    cell.appendChild(newText);

                    var cell = row.insertCell(3);
                    var newText = document.createTextNode(data.query.results.quote.Bid);
                    cell.appendChild(newText);

                    var cell = row.insertCell(4);
                    var newText = document.createTextNode(data.query.results.quote.PERatio);
                    cell.appendChild(newText);

                    var cell = row.insertCell(5);
                    var newText = document.createTextNode(data.query.results.quote.DividendYield);
                    cell.appendChild(newText);

                    var cell = row.insertCell(6);
                    var newText = document.createTextNode(data.query.results.quote.PriceBook);
                    cell.appendChild(newText);
            })
                .fail(function (jqxhr, textStatus, error) {
                var err = textStatus + ", " + error;
                    $("#status").text('Request failed: ' + err);
            });
        }
    </script>

    <script type="text/javascript">
        function deleteTicker() {
            var symbol = $("#inputSymbol").val();
            try {
            var table = document.getElementById("stockDataTable");
            var rowCount = table.rows.length;

            for(var i=0; i<table.rows.length; i++) {
                if(table.rows[i].cells[0].innerHTML == symbol) {
                    table.deleteRow(i);
                    i--;
                }
            }
            }catch(e) {
                alert(e);
            }
        }
    </script>


</body>
</html>

2 个答案:

答案 0 :(得分:2)

您可以: http://jsfiddle.net/KBJT4/10/

有几种方法可以对这只猫进行修饰,但这种方式是循环你quote结构的键。这是一些代码,但是运行小提琴才能看到它的实际效果。

/*simulating your data object*/
var data = {
      query: {
        results: {
          quote: {
            Symbol: 'Symbol_Value',
            StockExchange: 'StockExchange_Value',
            Ask: 'Ask_Value',
            Bid: 'Bid_Value',
            PERatio: 'PERatio_Value',
            DividendYield: 'DividendYield_Value',
            PriceBook: 'PriceBook_Value'
          }
        }
      }
    };

var i = 0;
var tempData = data.query.results.quote; /*shorten this up*/

//loop object by keys
for (var key in tempData) {
    i = i+1;

    //the alerts show you it's working
    //just replace the alerts with the commented out code

    //var cell = row.insertCell(i);
    alert('row.insertCell('+i+')');

    alert(key+': '+tempData[key]);

    //var newText = document.createTextNode('+tempData[key]+');
    var newText = tempData[key]; //you will remove this line also, its here just so the final alert will work
    alert('var newText = document.createTextNode('+tempData[key]+');');

    //cell.appendChild(newText);
    alert('cell.appendChild('+newText+');');
}

更新:我将此行添加到小提琴:alert(key+': '+data[key]);。它会帮助你更好地理解它。另外,如果你想显示键及其值而不仅仅是值,这就是你要做的。

更新: @ user3006803这是一个真实的工作示例,它不使用您的硬编码数据结构。它确实显示APL符号的一切

<强> http://jsfiddle.net/Dp8px/14/

(单击按钮后会看到出现的滚动条,结果块中有很多数据)

答案 1 :(得分:0)

这是网页的改进版,感谢gfrobenius的帮助。我还扩展了JavaScript代码,以便能够检索代码列表(以逗号分隔)。

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="en-GB" xml:lang="en-GB">

<head>
    <meta charset="UTF-8" /> 
    <title>
        Retrieve stock data from Yahoo Finance
    </title>
    <link rel="stylesheet" type="text/css" href="Yahoo_finance.css" />
    <script type="text/javascript" src="jQuery.js"></script>
</head>

<body>
    <input type="text" id="inputSymbols" />

    <table id='stockDataTable'>
        <thead>
            <tr>
            </tr>           
        </thead>
        <tbody>
        </tbody>
        <tfoot>
            <tr>
                <td colspan="3" id='status'></td>
            </tr>
        </tfoot>
    </table>

    <button type="submit" onClick="addTickers();">Add List of Tickers to Table</button>

    <script type="text/javascript">
        function addTickers() {
            var stringSymbols = $("#inputSymbols").val();
            var arraySymbols = stringSymbols.split(",");
            for (var i=0; i<arraySymbols.length; i++) {
                addTicker(arraySymbols[i]);
            }
        }
        function addTicker(symbol) {
            var url = "http://query.yahooapis.com/v1/public/yql";
            var data = encodeURIComponent("select * from yahoo.finance.quotes where symbol in ('" + symbol + "')");
            var table = document.getElementById("stockDataTable").getElementsByTagName('tbody')[0];

            $.getJSON(url, 'q=' + data + "&format=json&diagnostics=true&env=http://datatables.org/alltables.env")
                .done(function (data) {
                    //add table header to show symbols, if it does not exist
                    if (table.rows.length == 0) {
                        var tableHasHeader = false;
                        var rowHeader = table.insertRow(0);
                    } else {
                        var tableHasHeader = true;
                    }
                    var rowData = table.insertRow(table.rows.length);

                    //loop object by keys
                    var i = 0;
                    var tempData = data.query.results.quote;
                    for (var key in tempData) {

                        //add symbol to the header, if it was not populated yet
                        if (tableHasHeader == false) {
                            var cellHeader = rowHeader.insertCell(i);
                            var newText = document.createTextNode(key);
                            cellHeader.appendChild(newText);                
                        }

                        //add data
                        var cellData = rowData.insertCell(i);
                        var newText = document.createTextNode(tempData[key]);
                        cellData.appendChild(newText);

                        i = i + 1;
                    }
                    for (var i=0; i<table.rows.length; i++) {
                        if (typeof table.rows[i].cells[0].innerHTML === "undefined") {
                            alert("undefined");
                            table.deleteRow(i);
                        }                       
                    }
            })
            .fail(function (jqxhr, textStatus, error) {
                var err = textStatus + ", " + error;
                $("#status").text('Request failed: ' + err);
            });
            //alert(table.rows.length);
        }

    </script>

</body>
</html>