2

我正在尝试遍历来自 jQuery Ajax 请求的响应(以 XML 形式返回)。

有了这个响应,我正在构建一个包含 3 列的 HTML 表(可以有无限数量的行)。一旦找到第 4 个 XML 节点/“公司”,它应该在表中开始一个新行。非常感谢 JS 确定何时应添加新行的任何帮助。谢谢!

JS 示例:

/* jQuery Ajax Call here */

success: function(xml){  
    var trow = $("<tr>");  
    $(xml).find("Company").each(function(index){  
    var cellData = "<td width=\"33%\" valign=\"top\" ><div class=\"container\">"+
"<div class=\"item\"><a href=\"#\" title=\"\" target=\"\">"+ $(this).attr("Name")+ "</a></div>"+  
"<div class=\"description\">"+ $(this).attr("Description") + "</div></div></div></td>";  
    $(cellData).appendTo(trow);   
      });  
      trow.appendTo('#tbl');  
    }  
  });  

});

来自 Web 服务的示例 XML 响应:

<Companies>
    <Company ID="6" Name="Company name 1" Description="Lorem ipsum" />
    <Company ID="22" Name="Company name 2" Description="Lorem ipsum" />
    <Company ID="28" Name="Company name 3" Description="Lorem ipsum" />
    <Company ID="31" Name="Company name 4" Description="Lorem ipsum" />
</Companies>
4

1 回答 1

3

模运算符非常适合这样的事情。基本上它将一个数字除以另一个数字并返回余数。所以1 % 4 = 14 % 4 = 08 % 4 = 0

success: function(xml){
    var trow = $("<tr>"), table = $("#tbl");  
    $(xml).find("Company").each(function(index){  
        var cellData =  "<td width=\"33%\" valign=\"top\" ><div class=\"container\">"+
                        "<div class=\"item\"><a href=\"#\" title=\"\" target=\"\">"+ 
                        $(this).attr("Name")+ "</a></div>" +  
                        "<div class=\"description\">" + $(this).attr("Description") + 
                        "</div></div></div></td>";
        $(cellData).appendTo(trow);   
        if( (index + 1) % 4 == 0) {
            trow.appendTo(table);
            trow = $("<tr>");
        }

      });  
      if(trow.is(':not(:empty)')) trow.appendTo(table);  
    }  
    });
});

我还存储$("#tbl")在一个变量中以减少查找次数。

于 2009-12-12T05:44:34.170 回答