Pergunta

Eu sou analisar um arquivo XML e tentando retornar a saída para um div. No entanto, por alguma razão .append () parece não estar gerando a saída HTML correto.

Aqui está o JQuery trecho:

var list = $('<div class="response">').appendTo(this);
list.append('<ul>');

$('item',data).each(function(i){
    var dow = $(this).find("day").text();
    var high = $(this).find("high").text();
    var low = $(this).find("low").text();
    var conditions = $(this).find("conditions").text();
    var icon = $(this).find("icon").text();

    list.append('<li style="background: url(' + icon + '.gif) no-repeat;"><b>' + dow + '</b> - ' + conditions + ' (Hi: ' + high + ', Low: ' + low + ')</li>');          
});

O HTML isso produz é a seguinte:

<div class="response"></div>
<ul></ul>
    <li style="background: url(partlycloudy.gif) no-repeat;"><b>Wednesday</b> - Partly Cloudy (Hi: 50, Low: 43)</li>
    <li style="background: url(partlycloudy.gif) no-repeat;"><b>Thursday</b> - Partly Cloudy (Hi: 59, Low: 34)</li>
    <li style="background: url(partlycloudy.gif) no-repeat;"><b>Friday</b> - Partly Cloudy (Hi: 45, Low: 25)</li>
    <li style="background: url(chancesnow.gif) no-repeat;"><b>Saturday</b> - Chance of Snow (Hi: 36, Low: 22)</li>
    <li style="background: url(partlycloudy.gif) no-repeat;"><b>Sunday</b> - Partly Cloudy (Hi: 36, Low: 20)</li>
    <li style="background: url(partlycloudy.gif) no-repeat;"><b>Monday</b> - Partly Cloudy (Hi: 34, Low: 20)</li>

Qualquer idéia de por que as tags estão sendo fechados prematuramente? Eu estou em um pouco de perda. Se houver outra maneira que eu deveria estar fazendo isso eu apreciaria que você me apontar na direção certa.

Agradecemos antecipadamente!

Foi útil?

Solução

append() não é um acréscimo string. Ele está trabalhando no DOM ao vivo como você vai. Quando você anexar um <ul>, ele adiciona automaticamente a marca de fechamento. Tudo o que você adicionar à marcação após que vem mais tarde.

Em vez disso, tente isso.

var list = $('<div class="response">').appendTo(this);
var ul = $('<ul></ul>');

$('item',data).each(function(i){
    var dow = $(this).find("day").text();
    var high = $(this).find("high").text();
    var low = $(this).find("low").text();
    var conditions = $(this).find("conditions").text();
    var icon = $(this).find("icon").text();

    ul.append('<li style="background: url(' + icon + '.gif) no-repeat;"><b>' + dow + '</b> - ' + conditions + ' (Hi: ' + high + ', Low: ' + low + ')</li>');          
});
list.append(ul);

Outras dicas

Quando você anexar o UL, ele acrescenta um elemento totalmente formado e fechado. É melhor para construir todo o HTML como uma string e, em seguida, acrescentar o todo corda ao mesmo tempo.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top