【问题标题】:Problem with inserting a string containing html table rows (fetched by jquery ajax) into an html table - strange element jumble?将包含 html 表行(由 jquery ajax 获取)的字符串插入到 html 表中时出现问题 - 奇怪的元素混乱?
【发布时间】:2011-09-01 14:10:54
【问题描述】:

我试图在用户滚动时一点一点地加载网页内容,因为内容很大,而用户通常只对它的第一部分感兴趣。

页面由一张大桌子组成。每次用户滚动到页面底部时,我都会使用 ajax 获得更多行并将其附加到表格中。或者,我希望它以这种方式工作......

我的滚动事件正常工作。 ajax 请求按预期发送,我按预期获取数据。当我想将此数据附加到表中时,问题就开始了。

假设我对 ajax 请求(在我的脚本中称为“数据”)的回答是这样的字符串:

'<tr class="tasklist" id="r11">
   <td class="titlecell">Some kind of string title</td>
   <td>Some kind of string</td>
 </tr>
 <tr class="tasklist" id="r12">
   <td class="titlecell">Some other kind of string title</td>
   <td>Some other kind of string</td>
 </tr>'

然后我尝试使用 .after(data) 将这些行附加到我的表中。只有在网页上,那些出于某种奇怪原因的行会像这样插入到表格中:

'<tr>
   <td class="titlecell"></td>
   <td></td>
 </tr>
 <tr class="tasklist" id="r11"></tr>
 <tr>
   <td class="titlecell"></td>
   <td></td>
 </tr>
 <tr class="tasklist" id="r12"></tr>'

根本没有单元格内容,单元格被插入到额外的行中,将“原始”行留空。不是我想要的对吗?但为什么?你们中的任何一个网络预言机都可以通过解释我做错了什么或更好的(工作)解决方案应该是什么样子来让我重新回到正轨,我真的很感激!

这是我现在的 javascript 函数:

SPECIAL.loadMyTaskList = function() { 
  // to avoid multiple simultaneous function calls
  if ($('div #loader').html().trim() == '') {
    var last = $("#mytasklist .tasklist:last").attr("id");
    last = last.substring(1); // row id is on format r[number]
    $('div #loader').html('<img src="images/loading.gif" alt="Wait..."> Loading more tasks');
    $.get('includes/mytasklist.php?from='+last+'&nbr=10&ajax=1', function(data) {
      if (data=='')
        // all data is already loaded
        $(window).unbind('scroll'); 
      else 
        // append to table #mytasklist, after 
        // the last row (with class tasklist)
        $("#mytasklist .tasklist:last").after(data);
      // if browser window is so large, that the first 
      // post(s) of data fits without creating a scrollbar
      if (!BASIC.pageHasScrollbar())  
        SPECIAL.loadMyTaskList();
      $('div #loader').empty();
    });
  }
}

【问题讨论】:

  • 我自己终于找到了问题的答案。上面的代码没有问题。问题是我的 jquery 文件已损坏(但仍然是有效的代码,所以 firebug 没有捕捉到它)。我怀疑罪魁祸首是通过 search-n-replace 考虑得不那么周到。

标签: php jquery ajax


【解决方案1】:

试试这个代码,而不是 after 使用 append-

 $("#mytasklist").append(data);

如果你的桌子上有tbody,那么试试这个-

$("#mytasklist > tbody").append(data);

【讨论】:

  • 我们能搞定这个吗?
  • 小提琴什么?我的英语很有限... ;)
  • 您确认您的数据变量在 td 单元格中有文本吗?
  • 是的,我可以看到在 Firebug 中接收到的数据变量。那里没问题。
  • 这很简单。我不明白为什么会这样?如果你能在小提琴上重现问题会更好
【解决方案2】:

我终于自己找到了问题的答案。上面的代码没有问题。问题是我的 jquery 文件已损坏(但仍然是有效的代码,所以 firebug 没有捕捉到它)。我怀疑罪魁祸首是通过 search-n-replace 不那么深思熟虑的

【讨论】:

    猜你喜欢
    • 2016-02-13
    • 2020-05-31
    • 1970-01-01
    • 2013-11-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多