jQuery - 如果UL存在且有多少LI

时间:2010-08-27 16:46:13

标签: jquery

我在jQuery中寻找一种方法来检查UL是否存在以及是否确实计算了LI元素的数量。

如果要从数据库中提取新记录,以下jQuery会将UL加载到隐藏的DIV中:

j(".refreshMe").everyTime(5000,function(i){
    j.ajax({
      url: "refresh.php?latest="+className+"",
      cache: false,
      success: function(html){
        j(".refreshMe").html(html);
      }
    })
});

如果返回UL,我想计算列表中有多少LI元素,然后将该值写入页面。

如何在jQuery中实现这一目标?

1 个答案:

答案 0 :(得分:1)

你可以这样做:

j(".refreshMe").everyTime(5000,function(i){
    j.ajax({
      url: "refresh.php?latest="+className+"",
      cache: false,
      success: function(html){
        alert($("li", html).length); //number of <li> found
        j(".refreshMe").html(html);
      }
    })
});

success处理程序中,只需使用返回的数据作为查找的上下文,因此$("li", html)仅查找服务器响应中的<li>个元素,而.length是找到的计数,您可以获取该值并将其放在页面中所需的位置。

相关问题