2014-01-15 45 views
0

我希望我的jQuery腳本只返回找到的頂層節點,而不是遍歷所有節點。我在jQuery腳本中更改了哪些內容以實現該目標?我知道這與each(function) {}有關,但我不知道應該改變什麼。提前致謝!當使用jQuery解析XML時僅返回第一個節點

jQuery代碼:

$.ajax({ 
url: 'xml/timeline.xml', 
dataType: 'xml', 
success: function(data) { 
    $(data).find('channel item').each(function() { 
     var fbFeedWrapper = $('<div/>').addClass('fb-feed-wrapper'); 
     var fbFeedItem = $('<div />').addClass('fb-feed-item'); 
     $('.socialmedia-list#simlearn').append(fbFeedWrapper); 
     fbFeedWrapper.append(fbFeedItem); 

     var url = $(this).find('link').text(); 
     var title = $(this).find('title').text();   
     fbFeedItem.append($('<h1/>').html("<a href='" + url + "'>" + title + "</a>"));     
     var fbItemIcon = $('<div />').addClass('fb-item-icon'); 
     fbFeedItem.append(fbItemIcon); 
     var description = $(this).find('description').text(); 
         if (description.length > 80) { 
          description = description.substr(0, 80) + "..."; 
         } 
     fbFeedItem.append($('<div/>').addClass('fb-item-details').html(description));        

    }) 
} 


}); 

XML文件格式:

<channel> 
<item> // <-- If i Only want the top <item> node returned what should i do? 
    <title></title> 
    <link></link> 
    <description></description> 
</item> 
<item> 
    <title></title> 
    <link></link> 
    <description></description> 
</item> 
<item> 
    <title></title> 
    <link></link> 
    <description></description> 
</item> 

回答

1

而不是使用.each();只需找到第一個匹配的元素中。使用此對象指定一個變量,然後將.each()內的this引用的變量更改爲變量的名稱。

實施例(在這個例子中我命名變量self):

更改的行:

$(data).find('channel item').each(function() { 

爲:

var self = $(data).find('channel item').first(); 

然後,所有的this的發生的改變來是self。也除去.each功能的結束支架和支架(})

$.ajax({ 
    url: 'xml/timeline.xml', 
    dataType: 'xml', 
    success: function (data) { 
     var self = $(data).find('channel item').first(); 
     var fbFeedWrapper = $('<div/>').addClass('fb-feed-wrapper'); 
     var fbFeedItem = $('<div />').addClass('fb-feed-item'); 
     $('.socialmedia-list#simlearn').append(fbFeedWrapper); 
     fbFeedWrapper.append(fbFeedItem); 

     var url = $(self).find('link').text(); 
     var title = $(self).find('title').text(); 
     fbFeedItem.append($('<h1/>').html("<a href='" + url + "'>" + title + "</a>")); 
     var fbItemIcon = $('<div />').addClass('fb-item-icon'); 
     fbFeedItem.append(fbItemIcon); 
     var description = $(self).find('description').text(); 
     if (description.length > 80) { 
      description = description.substr(0, 80) + "..."; 
     } 
     fbFeedItem.append($('<div/>').addClass('fb-item-details').html(description)); 
    } 
}); 
0

嘗試這種情況:

$(data).find('channel item[0]') 
    //--------------------^^^-----add [0] to this 

:first

$(data).find('channel item:first') 

:eq()

$(data).find('channel item:eq(0)') 

即使你可以試試這個:

$(data).find('item:eq(0)') 
+0

當我試圖更換'$(數據).find( '通道項目')每個(函數(){'和'$(數據)。 find('channel item [1]')'jquery不會執行 – alchuang

+0

嘗試':eq(1)' – Jai