我只是想從XML文件中打印一個jQuery數組。這是我的代碼。我試圖從html代碼中看到打印stockList。另外,我是否正確地做了onBodyLoad?如何從xml數據使用jQuery打印數組?
HTML:
<body onload="onBodyLoad()">
<div id="stockList"></div>
<br />
<br />
<br />
<div id="stockInfo"></div>
</body>
的jQuery:
$(document).ready(function() {
$.ajax({
type: "GET",
url: "stocks.xml",
dataType: "xml",
success: function (onBodyLoad) {
var stocklist = new Array();
var stockinfo = new Array();
$(onBodyLoad).find('Stock').each(function() {
var company = $(this).find('Company').text();
var market = $(this).find('Market').text();
var sector = $(this).find('Sector').text();
var price = $(this).find('Price').text();
$(onBodyLoad).find('YearRange').each(function() {
var low = $(this).find('Low').text();
var high = $(this).find('High').text();
});
$(onBodyLoad).find('Dividend').each(function() {
var amount = $(this).find('Amount').text();
var yieldx = $(this).find('Yield').text();
var frequency = $(this).find('Frequency').text();
});
stocklist = $(company);
$('#stockList').append('<div><p>' + stocklist + '</p></div');
});
}
});
});
XML:
<Stock symbol="GOOG">
<Company>Google</Company>
<Market>NASDAQ</Market>
<Sector>Software</Sector>
<Price>$487.80</Price>
<YearRange>
<Low>$331.55</Low>
<High>$488.50</High>
</YearRange>
<Dividend available="false"/>
</Stock>
<Stock symbol="BA">
<Company>Boeing Company</Company>
<Market>NYSE</Market>
<Sector>Aerospace</Sector>
<Price>$79.05</Price>
<YearRange>
<Low>$63.70</Low>
<High>$89.58</High>
</YearRange>
<Dividend available="true">
<Amount>$1.20</Amount>
<Yield>$1.50</Yield>
<Frequency>QTR</Frequency>
</Dividend>
</Stock>
所需的輸出:
谷歌
波音公司
難道你.. 。試試運行它?除了兩個'.each()'調用不會做任何事情(他們所做的只是設置變量對回調函數是本地的),並且行'stocklist = $(company);'是很奇怪的因爲'company'包含'Company'元素的'text()',但它將被評估爲一個選擇器字符串。正如Bhushan所說,「onload =」onBodyLoad()「'是無效的和不必要的。 – tcovo 2013-03-28 03:58:31
Plz發佈xml代碼和您想要的輸出 – Sharun 2013-03-28 04:02:18