2012-03-05 35 views
1

我需要從包含以下格式的AJAX響應中獲取所有子div值。獲取jQuery AJAX響應中的所有子div值

var jqxhr = $.post('<%= url_for :action => :friend_list %>', { id: fid }, 
    function(data){ 
     var stripped_data = $(data).html().trim(); 
     var top_name = $(stripped_data).find('div.toppings_name').html(); 
    }); 

在stripped_data的警報中包含以下格式。

<div id="toppings> 
    <div class="toppings_name">a</div> 
    <div class="toppings_name">b</div> 
    <div class="toppings_name">c</div> 
</div> 

我嘗試使用.find()方法,但只獲得第一個子值。如何從父div獲取所有值。

回答

3

的問題是你使用html這是指在單個元素上使用,但實際使用它的集合。相反,你需要外部div的html內容。試試這個

var top_name = $(stripped_data).find('#toppings').html(); 

如果您正在尋找,雖然每個在div列表中的名稱,請嘗試以下

var all = []; 
$(stripped_data).find('div.toppings_name').each(function() { 
    var name = $(this).text(); 
    all.push(name); 
}); 
3

你應該使用jQuery的.each()功能結合來獲取所有的值:

$(stripped_data).find('div.toppings_name').each(function() { 
    // Process each topping here 
});