简体   繁体   English

为什么没有用each()创建多个标签?

[英]Why aren't multiple tags created with each()?

Let's say I've got some data that looks like this 假设我有一些看起来像这样的数据

<data>
    <location>
        <type>main</type>
    </location>
    <location>
        <type>mailing</type>
    </location>
</data>

and then some code that looks like this 然后是一些看起来像这样的代码

$('location',data).each(function(){

          var x='<table><tr><td>Type:</td><td>'+$(data).find('type').text()+'</td></tr></table>';
         $('#output').html(x);
});

The result I get from running this is 我从运行此得到的结果是

Type: mainmailing 类型:主邮件

I don't understand why it isn't doing the following since for each location element it should run the code again, right? 我不明白为什么它不执行以下操作,因为对于每个location元素,它应该再次运行代码,对吗?

Type: main 类型:主要

Type: mailing 类型:邮寄

Because you keep overriding the previous value. 因为您一直覆盖先前的值。

.html() does not append to the content that is in there, it overrides it. .html()不会追加到其中的内容,而是将其覆盖。

It is weird you are creating spearte tables and not just rows but the basic idea 您正在创建明细表,不仅是行,而且是基本概念,这很奇怪

var x='<table><tr><td>Type:</td><td>'+$(this).find('type').text()+'</td></tr></table>';
$('#output').append(x);

I would expect something more like 我希望有更多类似的东西

var table = "<table><tbody>";
$(data).find('location').each(function(){
   table += "<tr><th>Type:</th><td>'+$(this).find('type').text()+'</td></tr>';
});
table += "</tbody></table>";
$('#output').html(table);

You seem to be getting Type: mainmailing 您似乎正在输入Type: mainmailing

cause you seem to be finding it in the whole of data and not the current location tag. 因为您似乎在整个数据中找到了它,而不是在当前位置标记中找到了它。

$(data).find('type').text()

supposed to be 应该是

$(this).find('type').text();

Also you keep overriding the values in each loop iteration. 同样,您在每次循环迭代中继续覆盖值。 Move the appending to the outside of the loop. 将附件移到循环的外部。

var x = '<table>'
$('location','data').each(function(){
     x +='<tr><td>Type:</td><td>'+$(this).find('type').text()+'</td></tr>';   
});
x += '</table>'
$('#output').html(x);

Check Fiddle 检查小提琴

You should use append() instead of html() and you should use the item you are currently processing inside each() . 您应该使用append()而不是html()并且应该使用在each()内部当前正在处理的项目。

var data = "<data><location><type>main</type></location><location><type>mailing</type></location></data>";

$('location', data).each(function(index, item) {
    var x = '<table><tr><td>Type:</td><td>' + $(item).find('type').text() + '</td></tr></table>';
    $('#output').append(x);
});​

Here's a working demo . 这是一个工作示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM