gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 14:20:04 25 4
gpt4 key购买 nike

我试图将具有相同属性的 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com