按值过滤.data()对象中的项

Filtering items in .data() object by value

本文关键字:对象 过滤 data      更新时间:2023-09-26

编辑:忘记jsfield

我有一个由许多路径/形状组成的SVG图像,每个图像都包含在具有id<g>元素中。为了简单起见,我将示例限制为两个形状。

我也有一系列的<div> s -代表几种颜色-其中有一个data-attribute,可以匹配SVG形状<g> id。所以:

<svg width="428" height="230" xmlns="http://www.w3.org/2000/svg">
 <g id="square">
  <rect height="91" width="91" y="68.5" x="82.5"/>
 </g>
 <g id="circle">
  <ellipse ry="48" rx="48" id="svg_2" cy="111.5" cx="295.5"/>
 </g>
</svg>
<div class="colors" data-square="5" data-circle="0">Red</div>
<div class="colors" data-square="1" data-circle="3">Blue</div>
<div class="colors" data-square="0" data-circle="9">Green</div> 

点击.color <div>,我想:

  1. 在对象中存储所有属性(键和值)(完成),

  2. 过滤掉任何小于1的属性(我不能弄清楚的部分)

  3. 然后添加一个类(.active)到任何svg <g>元素与id匹配的属性键(完成,没有过滤)。

这是我的jQuery,以及我试图过滤data()对象的注释:

var shapes = $('svg g');
$('.colors').click(function () {
    //remove active class from all shapes
    $(shapes).attr("class", "");
    //store data attributes
    var colortotals = $(this).data();
    //filter attributes greater than 0
    //var colortotals = $(this).data().filter(function() {
      //return $(this) > "0";
    //});
    //add active class to any shape with id matching an attribute key
    $.each(colortotals, function(key, value) {
      alert(key + ": " + value);
      $(shapes).filter('#' + key).attr("class", "active");
    });
});

这是你要找的吗?

$.each(colortotals, function(key, value) {
    if (Number(value) > 0) {
      $(shapes).filter('#' + key).attr("class", "active");
    }
});
http://jsfiddle.net/rMBPP/31/

对不起,如果我没有理解正确的问题