2012-07-09 73 views
0

我試圖通過解析XML填充兩個dimensoinal數組,但我的函數不存儲第一個項目爲某些未知的原因。 (因此,它正確存儲[0] [1]和[1] [1],但不存儲[0] [0]和[0] [1]);爲什麼它返回undefined? (JQuery的XML解析問題)

陣列結構背後的想法是:

first word- > first choice ->[0][0]; 
first word -> second choice ->[0][1]; 
second word -> first choice ->[1][0]; 
... you can guess 

它告誡每次(只是爲了檢查櫃檯是正確的。)

的XML:

<?xml version="1.0" encoding="utf-8" ?> 
<Page> 
    <Word id = "0"> 
    <Choice id = "0"> 
    <text>First word - 1. choice</text> 
    </Choice> 
    <Choice id = "1"> 
    <text>First word - 2. choice</text> 
    </Choice> 
    </Word> 
<Word id= "1"> 
    <Choices> 
    <Choice id = "0"> 
     <text>Second word - First choice</text> 
    </Choice> 
    <Choice id= "1"> 
    <text>Second word - Second Choice</text> 
    </Choice> 
    </Choices> 
</Word> 
</Page> 

功能:

$(document).ready(function() 
{ 
$.ajax({ 
type: "GET", 
url: "xml.xml", 
dataType: "xml", 
success: parseXml2 
    }); 
}); 

function parseXml2(xml) { 

var myArray = []; 
var a = 0; 

$(xml).find("Word").each(function() { 
    var i = $(this).attr("id"); 
    a = 0; 

    $(this).find("Choice").each(function() { 
     alert('I:' + i + 'A:' + a); 
     alert('Id:' + $(this).attr("id") + $(this).text()); 
     myArray[i] = []; 
     var text = $(this).text(); 
     myArray[i][a] = text; 
     a++; 
    }); 
}); 

alert(myArray[0][0]); 

} 

parseXml2(xml);​ 

該代碼也可以找到here

+1

今後請在所有相關的代碼,你沒有書面方式它你帖子和**不要**只是包括一個鏈接到jsFiddle。您的帖子應該獨立於任何其他資源;想想如果jsFiddle將來會發生什麼事情。 – Matt 2012-07-09 09:44:33

+0

好吧,我已經添加了我的代碼!從現在起每次都會這樣做! – Levela 2012-07-09 09:58:07

回答

2

這是因爲您在每次迭代時都設置了myArray[i] = [];。把它設置在這個循環中,不是第二個。 vágod:D?

這應該工作:

$(xml).find("Word").each(function() { 
    var i = $(this).attr("id"); 
    a = 0; 
    myArray[i] = []; 
    $(this).find("Choice").each(function() { 
     alert('I:' + i + 'A:' + a); 
     alert('Id:' + $(this).attr("id") + $(this).text()); 

     var text = $(this).text(); 
     myArray[i][a] = text; 
     a++; 
    }); 
}); 
+0

謝謝! :D我再次錯過了明顯的......(kösziwazze!:D) – Levela 2012-07-09 10:06:24

+0

azértez nem volt annyira顯然:D egy ideig elszarakodtam vele:D – 19greg96 2012-07-09 10:07:47

0

的問題在你的代碼在於myArray[i] = [];線。

使用這一行,您將在每次迭代中重新定義數組。

一個解決方案來克服,這將是寫

if(typeof(myArray[i]) === "undefined"){ 
    myArray[i] = []; 
} 

,以確保如果存在

Updated fiddle