【发布时间】:2013-04-06 07:43:26
【问题描述】:
我正在尝试使用 jQuery mobile 解析 XML 文件。这是我的 jQuery 脚本:
<script>
$(document).ready(function(){
$.ajax({
type: "GET",
url: "bars.xml",
dataType: "xml",
success: function(xml) {
$(xml).find('bar').each(function(){
var date = new Date();
var day = date.getDay();
var name = $(this).attr('name');
var id = $(this).attr('id');
var specials = $(this).find('specials').text();
if (id == day)
{
$('<li data-role="list-divider" id="link_'+id+'"></li>').html(name).appendTo('#daily-specials');
$('<li class="specials"></li>').html(specials).appendTo('#link_'+id);
}
});
});
});
});
</script>
还有我的 XML 文件:
<?xml version="1.0" encoding="iso-8859-1"?>
<bars>
<!-- Friday specials for bar one -->
<bar name="Bar One" id="5">
<specials>
Special 1 <br />
Special 2 <br />
Special 3 <br />
Special 4 <br />
Special 5
</specials>
</bar>
<!-- Saturday specials for bar one -->
<bar name="Bar One" id="6">
<specials>
Special 1 <br />
Special 2 <br />
Special 3 <br />
Special 4 <br />
Special 5
</specials>
</bar>
</bars>
谁能看到我做错了什么?如您所见,我正在尝试获取一周中当天的“Bar One”的特别信息,然后将该信息传递给我页面上的 HTML 类。不过,我的网站上没有打印出来。如果我什至不接近,我深表歉意,但方向会有所帮助。谢谢!
【问题讨论】:
-
您必须将索引和元素传递给每个函数,如下所示: $(xml).find('bar').each(function(index, barInstance) [...] 然后只需访问它 var specials = barInstance.find('specials').text();
-
好吧,它对我有用jsfiddle.net/c3pnc
-
如果所有的栏都有相同的描述; “name = bar One”那你为什么要基于那个搜索.....???您可以在每个循环中使用每个条搜索您的数据!!!
-
尝试使用$.parseXML(xml)
-
您是在周日、周一、周二、周三还是周四运行的?
标签: jquery xml jquery-mobile xml-parsing