我需要从包含以下格式的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中获取所有值。
答案 0 :(得分:3)
你应该结合使用jQuery的.each()
函数来获取所有值:
$(stripped_data).find('div.toppings_name').each(function() {
// Process each topping here
});
答案 1 :(得分: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);
});