【问题标题】:Broken HTML From AJAX Request Using JQuery使用 JQuery 从 AJAX 请求中破坏 HTML
【发布时间】:2010-12-22 12:54:19
【问题描述】:

我正在解析一个 XML 文件并尝试将输出返回到一个 div。但是,由于某种原因,.append() 似乎没有生成正确的 HTML 输出。

这里是 JQuery sn-p:

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>');          
});

生成的 HTML 如下:

<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>

知道标签过早关闭的原因吗?我有点不知所措。如果有其他方法我应该这样做,我会很感激你指出我正确的方向。

提前致谢!

【问题讨论】:

    标签: jquery html ajax append


    【解决方案1】:

    当您附加 UL 时,它会附加一个完全形成且闭合的元素。最好将整个 HTML 构建为一个字符串,然后一次附加整个字符串。

    【讨论】:

      【解决方案2】:

      append() 不是字符串追加。随着您的使用,它正在处理实时 DOM。当您附加 &lt;ul&gt; 时,它会自动添加结束标记。之后添加到标记中的任何内容。

      相反,试试这个。

      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);
      

      【讨论】:

      • 完美运行。谢谢车坦!
      猜你喜欢
      • 1970-01-01
      • 2013-11-11
      • 2017-02-06
      • 1970-01-01
      • 2019-05-29
      • 1970-01-01
      • 2012-01-01
      • 1970-01-01
      • 2013-11-29
      相关资源
      最近更新 更多