在选择 Accordion 时,我正在捕获点击事件并尝试读取 xml 文件并解析它。
我有以下 xml 文件,它是我在 javascript 本身中定义的。
<categories>
<category id="2" name="Pepsi" >
<products>
<product id="858" name="7UP" price="24.4900" />
<product id="860" name="Aquafina" price="24.4900" />
</products>
</category>
<category id="4" name="Coke" >
<products>
<product id="811" name="ThumpsUp" price="24.4900" />
<product id="813" name="Maaza" price="24.4900" />
</products>
</category>
</categories>
但是我无法解析 xml 文件。
这样,一旦我从 xml 解析中获取元素,我就可以将其添加到 h4 中。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Basic jQuery Accordion</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript" src="http://code.jquery.com/ui/1.10.2/jquery-ui.js"></script>
<link rel="stylesheet" type="text/css" href="http://code.jquery.com/ui/1.10.2/themes/dark-hive/jquery-ui.css" />
<script type="text/javascript">
var xmldocu = '<categories><category id="2" name="Pepsi" ><products><product id="858" name="7UP" price="24.4900" /><product id="860" name="Aquafina" price="24.4900" /></products></category><category id="4" name="Coke" ><products><product id="811" name="ThumpsUp" price="24.4900" /><product id="813" name="Maaza" price="24.4900" /></products></category></categories>' ;
$(document).ready(
function () {
$("#accordion").accordion({ header: "h3",
autoheight: false,
active: false,
alwaysOpen: false,
fillspace: false,
collapsible: true,
//heightStyle: content //auto, fill, content
});
$("#accordion").accordion({
activate: function(event, ui) {
var selectedeleemnt = ui.newHeader.text();
if(selectedeleemnt=="Javascript")
{
$(xmldocu).find("categories").each(function () {
var tsq = $(this).find("category").attr('name').text();
alert(tsq);
});
}
}
});
});
</script>
</head>
<body>
<div style="width: 468px;">
<div id="accordion">
<h3><a href="#">Javascript</a></h3>
<div>
<h4>Testt</h4>
</div>
<h3><a href="#">Other</a></h3>
<div>
<h4>Stuff</h4>
</div>
</div>
</div>
最佳答案
调用 find("categories")
不起作用,因为 categories
是根节点。您已经在上面了,find
会查找后代节点。
您的下一个问题是 attr
返回一个字符串,因此您不需要对其调用 text
。
以下代码符合您的预期:
$(xmldocu).find("category").each(function () {
var tsq = $(this).attr('name');//.text();
alert(tsq);
});
关于javascript - 无法通过 jQuery 解析 xml 属性。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23761718/