简体   繁体   中英

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?

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.

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

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() .

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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