2014-02-11 72 views
1

我編寫了以下JavaScript函數以從Yahoo Finance獲取股票信息。我想與一個簡化的代碼循環,以避免重複這些三行:如何通過for循環簡化我的JavaScript函數?

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> 
+0

我看到'''Symbol','StockExchange',...]'這樣的數組在'quoteSymbol'和'quote [array [0]]'是等價的。 – tadman

+0

出了什麼問題?你有錯誤嗎? – showdev

+0

是的,對不起。我收到以下錯誤信息:類型錯誤:data.query未定義 \t VAR dataElement = \t [\t data.query.results.quote.Symbol, – lcazarre

回答

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/

(單擊該按鈕通知出現的滾動條,有很多數據在結果框後)

+0

非常感謝你的幫助。這是修改後的腳本:http://jsfiddle.net/lcazarre/Gc5bd/。儘管如此,我還是沒能成功。我收到以下錯誤消息:「NetworkError:400 Bad Request - http://query.yahooapis.com/v1/public/yql?q=[object%20Object]&format=json&diagnostics=true&env=http://datatables.org/ alltables.env」。 – lcazarre

+0

我會稍微檢查一下,~30分鐘 – gfrobenius

+0

@ user3006803你的小提琴有許多問題。很多代碼根本無法運行在缺少代碼的小提示中,它不是一個完整的功能性網頁。 (1)我將股票代碼硬編碼爲'APL'(即使它未被使用,您的數據是硬編碼的)(2)當您在JavaScript塊中時,您不需要'

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>