我正在嘗試使用select元素來生成jQuery和XML的動態輸出。但是當我到達if語句時,XML每個循環僅使用三明治上的第一個ID。如何使if語句針對選定的ID測試每個三明治ID?每次運行它時,它都會爲四個循環中的每一個使用「意大利」ID。使用循環產生XML輸出?
<!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>
爲什麼$三明治?我的意思是你爲什麼使用$與一個變量只要說'var sandwich = data.find(「sandwich」);' – progrAmmar