Javascript jqueryeach();生成html元素只返回最后一个值

Javascript jqueryeach();生成html元素只返回最后一个值,javascript,jquery,html,xml,Javascript,Jquery,Html,Xml,我正在尝试从XML数据动态填充HTML。我只需要某些值。我设法做到了每一个;当我把它记录在控制台上时,一切都会完美地输出,但当我尝试为每个对象生成HTML代码时,我只从最后一个对象中获取数据,只生成1个div 下面是示例代码: XML: jQuery: 使用这段代码,我只得到1个div生成的一些文本…3个来自XML。 控制台日志正确输出所有3个日志的值 从阅读其他资料来看,我想我在HTML生成部分搞砸了,因为它只会生成上一次迭代中的数据,但我对这方面相当陌生,不知道我做错了什么 感谢您的帮助 我

我正在尝试从XML数据动态填充HTML。我只需要某些值。我设法做到了每一个;当我把它记录在控制台上时,一切都会完美地输出,但当我尝试为每个对象生成HTML代码时,我只从最后一个对象中获取数据,只生成1个div

下面是示例代码:

XML:

jQuery:

使用这段代码,我只得到1个div生成的一些文本…3个来自XML。 控制台日志正确输出所有3个日志的值

从阅读其他资料来看,我想我在HTML生成部分搞砸了,因为它只会生成上一次迭代中的数据,但我对这方面相当陌生,不知道我做错了什么


感谢您的帮助

我现在不再使用jQuery了,但似乎每次都在替换包装中的HTML,而不是像@Giacomo cosmato所说的那样添加新的div

,每次都使用.HTML来删除内容,这会更改元素的内容,相反,您需要使用.append,它将向元素添加内容:

$document.readyfunction{ $sms.eachfunctionindex,值{ 如果$this.attrtype==1{ 发送方=名称1; divClass=class1; pClass=pclass1; }如果$this.attrtype==2,则为else{ 发送方=名称2; divClass=class2; pClass=pclass2; } text=$this.attrbody; 日期=$this.attr\u日期; $'.mainwrap'.append $'

'+sender+'

'+text+'

'+date+'

; }; }; .mainwrap{ 边框:1px实心; }
<sms protocol="0" address="+00000000000" date="1514988026768" type="2" subject="null" body="Some text...1" toa="null" sc_toa="null" service_center="null" read="1" status="-1" locked="0" date_sent="0" readable_date="3 Jan 2018 15:00:26" contact_name="Name1" />
<sms protocol="0" address="+00000000000" date="1514988062956" type="1" subject="null" body="Some text...2" toa="null" sc_toa="null" service_center="+00000000" read="1" status="-1" locked="0" date_sent="1514988062000" readable_date="3 Jan 2018 15:01:02" contact_name="Name1" />
<sms protocol="0" address="+00000000000" date="1515074431967" type="1" subject="null" body="Some text...3" toa="null" sc_toa="null" service_center="+000000000" read="1" status="-1" locked="0" date_sent="1515074430000" readable_date="4 Jan 2018 15:00:31" contact_name="Name1" />
$(document).ready(function(){
$( "sms" ).each(function(index, value){
if ($(this).attr("type") == 1) {
    sender = "name1";
    divClass = "class1";
    pClass = "pclass1";
}else if ($(this).attr("type") == 2) {
    sender = "name2";
    divClass = "class2";
    pClass = "pclass2";
}
text = $(this).attr("body");
date = $(this).attr("readable_date");

$('.mainwrap').html(
$('<div class="'+divClass+'"><p class="senderName">'+sender+'</p><p class="'+pClass+'">'+text+'</p><p class="dates">'+date+'</p>    </div>'));
   });
 });