我只是想从XML文件中打印一个jQuery数组。这是我的代码。我正在尝试打印stockList,你可以从html代码中看到。另外,我是否正确执行了onBodyLoad?
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>
期望的输出:
谷歌
波音公司
答案 0 :(得分:1)
收集公司名称,对其进行排序并打印:
$(document).ready(function () {
$.ajax({
type: "GET",
url: "stocks.xml",
dataType: "xml",
success: function (xmlData) {
var companyNames = [];
$(xmlData).find('Stock').each(function () {
var company = $(this).find('Company').text();
companyNames.push(company);
});
companyNames.sort();
$.each(companyNames, function (index, name) {
$('#stockList').append('<div><p>' + name + '</p></div>');
});
}
});
});
答案 1 :(得分:0)
像这样修改你的代码:
<body>
<div id="stockList"></div>
</body>
<强>脚本:强>
$(document).ready(function () {
$.ajax({
type: "GET",
url: "stocks.xml",
dataType: "xml",
success: function(xml){
var newArray = [];
$(xml).find('Stock').each(function () {
var company = $(this).find('Company').text();
newArray.push(company );
});
newArray.sort();
$(companyNames).each( function (index, name) {
$('#stockList').append('<div><p>' + name + '</p></div>');
});
}
});
});