1

我很快就使用以下脚本为脚本制作了这个函数:

$.fn.liCount = function(){
    var i=0;
    $(this).children().each(function(){
        i++;
    });
    return Number(i);
}

问题是IE返回0,有人知道为什么吗?

alert( $("ul").liCount() );

编辑:

<div id="prev-quotes">
    <ul id="quote-list">
        <li id="quote_content_wrapper" >
            <ul>
                <li class="quote_li">
                    <span class="service_quote"><a href="#">Web Design Services</a></span>
                    <br>
                    <span class="cost_quote"><strong>£192</strong> - <a id="7" href="#">delete</a> | <a id="7" href="#">view</a></span>
                </li>
                <li class="quote_li">
                    <span class="service_quote"><a href="#">Web Design Services</a></span>
                    <br>
                    <span class="cost_quote"><strong>£192</strong> - <a id="7" href="#">delete</a> | <a id="7" href="#">view</a></span>
                </li>
                <li class="quote_li">
                    <span class="service_quote"><a href="#">Web Design Services</a></span>
                    <br>
                    <span class="cost_quote"><strong>£192</strong> - <a id="7" href="#">delete</a> | <a id="7" href="#">view</a></span>
                </li>
            </ul>
        </li>
        <li>
            <a id="first-quote" href="#">Previous Quotes</a>
            <img height="16" width="16" id="warning" src="images/for_web/check_mark.png">
        </li>
    </ul>    
</div>
4

3 回答 3

1

你可以简单地使用

$("ul > li").length;

参见子选择器(“父>子”)

如果你想用 id获取li里面的数量,你可以使用ulquote-list

$("#quote-list > li").length;

如果要获取类名quote_li的li个数,可以使用

$("#quote-list > li > ul > li.quote_li").length;
于 2010-02-25T09:14:47.680 回答
0

return Number(i);当您确定i是数字时,无需使用。

你甚至根本不需要计数器变量——.length在 jQuery 中有。

为什么不直接使用以下内容:

$.fn.liCount = function() {
 return $(this).children('li').length;
};

它更短、更快、更具可读性,并且适用于所有浏览器

但是,为此编写“插件”似乎有点冗长/不必要。你可以使用类似的东西:

$('ul > li').length;
于 2010-02-25T09:10:27.687 回答
0

在 IE 7 和 8 中,您需要识别子标签

$.fn.liCount = function(){
    var i=0;
    $(this).children("li").each(function(){
        i++;
    });
    return Number(i);
}

将工作。当然,这会限制该方法的使用,除非您传入要计算的元素,例如...

    $.fn.liCount = function(elem){
        var i=0;
        $(this).children(elem).each(function(){
            i++;
        });
        return Number(i);
   }

然后打电话

警报($(“ul”).liCount(“li”));

于 2011-08-16T16:27:43.623 回答