2010-09-19 43 views
1

jQuery的新手,我有一個從XML文件返回數據的腳本。我需要的是返回元素的索引號。我知道我可以retreve一個單一的元素與這一使用jQuery從XML中獲取元素的索引值

name = $("sitelist:eq(1)",data).text(); 

但在我的劇本我需要知道所顯示的數據的每個元素的位置。 類似position = $(data,eq).value。可以幫助任何人。

$(document).ready(function() { 

    $.ajax({ 
     type: "GET", 
     url: "sites.xml", 
     dataType: "xml", 
     success: displayXml 
    }); 

    function displayXml(data) { 
     $(data).find("course").each(function() { 
      var name = $(this).find("sitelist").text(); 
      var line1 = $(this).find("address1").text(); 
     }); 
    } 
}); // doc ready 

回答

3

我不知道你需要的指數,這點,但如果是,你遍歷與.each()course你可以從每次迭代的索引.each()

$(data).find("course").each(function(idx) { 
     alert(idx); // will alert the index of the current "course" 

     var name = $(this).find("sitelist").text(); 
     var line1 = $(this).find("address1").text(); 
}); 

如果還有其他一些情況,可以嘗試使用.index()方法從其兄弟中獲取節點的索引。 它需要jQuery 1.4或更高版本。

如:

var $sitelist = $(this).find("sitelist"); 
var index = $sitelist.index(); 
var name = $sitelist.text();