javascript - 使用javascript对具有相同属性的div进行分组

标签 javascript jquery html css

我试图将具有相同属性的 div 分组并将它们放入容器 div 中。生成了 div。结构看起来像这样。

<div class="cleanse">A</div>
        <div class="treat">B</div>
        <div class="prime">C</div>

        <br><br><br>
        <div class="product"><img alt="red" src="http://aar.co/508-859-thickbox/therapy-ball-small-red.jpg" width="100px"></div>
        <div class="product"><img alt="blue" src="http://www.valleyvet.com/swatches/11178_L_230_vvs.jpg" width="100px"></div>
        <div class="product"><img alt="red" src="http://aar.co/508-859-thickbox/therapy-ball-small-red.jpg" width="100px"></div>
        <div class="product"><img alt="yellow" src="http://debenhams.scene7.com/is/image/Debenhams/304028400423?$ProdLarge$" width="100px"></div>
        <div class="product"><img alt="blue" src="http://www.valleyvet.com/swatches/11178_L_230_vvs.jpg" width="100px"></div>

到目前为止我所拥有的脚本是不工作的

$(function(){
        $('.product').each(function(){
            if ($(this).is('[red]')) {
                $(this).appendTo($('.cleanse'));
            } else {
                 if ($(this).is('[blue]')) {
                        $(this).appendTo($('.treat'));
                 } else {
                      if ($(this).is('[yellow]')) {
                        $(this).appendTo($('.prime'));  
                      }
                 }
            }
            }
    });

最佳答案

使用 has过滤器:

$(function() {
    var $products = $('.product');

    $products.filter(':has([alt=red])').appendTo('.cleanse');
    $products.filter(':has([alt=blue])').appendTo('.treat');
    $products.filter(':has([alt=yellow])').appendTo('.prime');
});

这是 fiddle :http://jsfiddle.net/qxRY4/1/


如果您要处理更大的数据集,您可能想改用循环。方法如下:

$(function() {
    var $products = $('.product');
    var map = {
        red: 'cleanse',
        blue: 'treat',
        yellow: 'prime'
    };

    $.each(map, function (attr, className) {
        $products.filter(':has([alt=' + attr + '])').appendTo('.' + className);
    });
});

这是 fiddle :http://jsfiddle.net/qxRY4/2/

关于javascript - 使用javascript对具有相同属性的div进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14249970/

相关文章:

javascript - Titanium 项目的正确 CommonJS 结构是什么?

javascript - 如何在不使用 jQuery 的情况下使用 JavaScript 在 id 之后移动 HTML 标记?

jquery - 清除表单,但保留单选按钮/复选框/隐藏的值

javascript - 无法在此代码中获取 this.value

html - CSS:如何使用 flexbox 控制不同大小图像库中的最大增长比率

javascript - 它使用 ASP.NET MVC 和 javascript 在 TreeView 中显示 "undefined"

javascript - 查询以匹配数组输入

javascript - JQuery 只查看一个 DIV ID 来获取值

html - 关于需要特定 HTML 结构的混合的想法?

jquery - CSS 宽度不适用于 <ul> <li> <label> 等