【问题标题】:Count images or "rel" attribute计算图像或“rel”属性
【发布时间】:2013-02-26 18:45:50
【问题描述】:

我想分别计算一个<div class="thumbnail"> 的所有图像。

我的代码:

    <div class="thumbnail">     

    <a rel="first" href="#">
        <div>
        <div></div>
        <img src="...">
        </div>
    </a>

    <div class="hidden-fb"> <!-- // CSS display: none -->                                                                                                 
        <a rel="first" href="#">
            <div>
            <div></div>
            <img src="...">
            </div>
        </a>                                               
    </div><!-- .hidden-fb -->

</div><!-- .thumbnail -->

<h2>Contains 2* images </h2>

我试试这个

var featureImageCount = $('div.thumbnail img').length;    
$('div.thumbnail').after('<div><h1>' + featureImageCount + ' Images</h1></div>');

但我只为所有 div "(6)"
我可以用 jquery 做到这一点,图像的数量*会自动填写吗?
或者jquery可以通过不同的rel属性来统计项目吗?

jsFiddle

谢谢
奥格尼

【问题讨论】:

    标签: jquery image count each rel


    【解决方案1】:

    您需要使用.each 单独查看每个.thumbnail 元素。然后,您可以在回调中使用$(this) 来访问实际元素。从那里,您可以找到所有特定的后代 &lt;img&gt; 元素。从那里,您可以像尝试一样使用.after,使用$(this)

    $(document).ready(function () {
        $("div.thumbnail").each(function () {
            var $this = $(this),
                count = $this.children("a").children("img").length;
            $this.after("<div><h1>" + count + " Images</h1></div>");
        });
    });
    

    http://jsfiddle.net/yCazz/8/

    【讨论】:

    • 谢谢。我更新了你的小提琴,因为我只有“1”:[link]jsfiddle.net/yCazz/4
    • @ogni 你可能看过一个奇怪的版本。如果您现在看一下我在答案中的小提琴,它似乎对我有用-显示“3”、“2”、“1”
    • 谢谢。我也更新了我的版本,因为我的代码结构不正确,并且一些图像是display: none,我使用了一个只有一个链接预览图像的 fancybox 库。
    【解决方案2】:
    $('div.thumbnail').each(function () {
    
        var $this = $(this),
            count = $this.find('img').length;
    
        $this.after('<h2>', {
            text: 'Contains (' + count  + '*) image' + (count == 1 ? '' : 's')
        });
    
    });
    

    【讨论】:

    • 谢谢 - 我完成了$('.thumbnail').each(function () { var $this = $(this), count = $this.find('a').length; $this.after("&lt;div&gt;&lt;h1&gt;" + count + " Images&lt;/h1&gt;&lt;/div&gt;"); });
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多