我正在尝试使用select元素来生成带有jQuery和XML的动态输出。但是当我到达if语句时,XML每个循环只使用三明治上的第一个ID。如何使if语句根据所选ID测试每个三明治ID?每次运行它时,它只对四个循环中的每一个使用“TheItalian”ID。
<!DOCTYPE HTML>
<html>
<head>
<title>Sandwiches</title>
<link rel="stylesheet" type="text/css" href="css/reset.css"/>
<link rel="stylesheet" type="text/css" href="css/site.css"/>
<script language="javascript" type="text/javascript" src="jquery-2.1.0.min.js"></script>
</head>
<body>
<header>
<h1>Nick's Sandwich Shop</h1>
</header>
<section id="main">
<section id="selection">
<h2>Please select a sandwich</h2>
<select id="selector">
<option>Select One...</option>
<option id="TheItalian">The Italian</option>
<option id="BLTPlus1">BLT+1</option>
<option id="TheBillyClub">The Billy Club</option>
<option id="FrenchDip">French Dip</option>
</select>
</section>
<script>
$(document).ready(function() {
$("#selector").change(function() {
var sandwichChoice = $(this).children(":selected").attr("id");
$.ajax({
url: "sandwiches.xml",
dataType: "xml",
success: function(data){
var $xml = $(data);
var $sandwich = $xml.find("sandwich");
alert($sandwich.length);
$sandwich.each(function(){
console.log($sandwich.attr("id"));
console.log(sandwichChoice);
if ($sandwich.attr("id" ) == sandwichChoice) {
var $name = $(this).find("name");
alert($name.text());
};
});
}});
});
});
</script>
</section>
</body>
</html>
我的XML数据
<sandwiches>
<sandwich id="TheItalian">
<name>The Italian</name>
<bread>Italian</bread>
<meat>Black forest ham and salami</meat>
<cheese>Provolone</cheese>
<veggies>Lettuce, tomatoes, onions, and mild peppers</veggies>
<dressing>Italian oil</dressing>
</sandwich>
<sandwich id="BLTPlus1">
<name>BLT+1</name>
<bread>Sourdough</bread>
<meat>Bacon and more bacon</meat>
<cheese>Cheddar</cheese>
<veggies>Lettuce and tomatoes</veggies>
<dressing>Spicy garlic mayo</dressing>
</sandwich>
<sandwich id="TheBillyClub">
<name>The Billy Club</name>
<bread>Rye</bread>
<meat>Turkey, bacon and black forest ham</meat>
<cheese>Cheddar and Swiss</cheese>
<veggies>Lettuce, tomatoes, </veggies>
<dressing>Honey mustard and mayo</dressing>
</sandwich>
<sandwich id="FrenchDip">
<name>French Dip</name>
<bread>Baguette</bread>
<meat>Roast beef</meat>
<cheese>Melted Cheddar</cheese>
<veggies>Grilled onions</veggies>
<dressing>Au jus</dressing>
</sandwich>
</sandwiches>
答案 0 :(得分:0)
考虑这个修订的jQ用于AJAX成功回调:
success: function(xml){
$(xml).find("sandwich").each(function(){
if ($(this).attr("id" ) == sandwichChoice) {
var $name = $(this).find("name");
alert($name.text());
};
});
}
我相信这个问题就在这一行......
if ($sandwich.attr("id")
...因为$sandwich
是XML中所有三明治项目的jQ集合,而不是一个三明治。
此外,如果您不反对/无法使用&lt; option&gt;上的“value”属性元素,选择你的'sandwichChoice'会更容易出现“value”属性:
$("#selector").change(function() {
var sandwichChoice = $(this).val();
...
});