【问题标题】:d3 map with checkbox filtering带有复选框过滤的d3映射
【发布时间】:2013-02-23 19:03:35
【问题描述】:

我制作了一个 d3 符号地图,并希望用户能够通过名为“类型”的属性过滤点。共有三种类型:a、b、c,每种都有一个关联的 html 复选框,选中时应显示类型 a 的点,未选中时应删除这些点。我想知道将检查/取消检查事件传递到 d3 的最佳方法是什么?我在想如果有办法将检查的类型传递给 select.filter(),那将是最好的方法。代码如下:

HTML

<div class="filter_options">
<input class="filter_button" id="a_button" type="checkbox">a</input><br>
<input class="filter_button" id="b_button" type="checkbox">b</input><br>
<input class="filter_button" id="c_button" type="checkbox">c</input><br>
</div>

js

queue()
.defer(d3.json, "basemap.json")
.defer(d3.json, "points.json")
.await(ready);

function ready(error, base, points) {

var button = 

svg.append("path")
  .attr("class", "polys")
  .datum(topojson.object(us, base.objects.polys))
  .attr("d", path);

svg.selectAll(".symbol")
  .data(points.features)
.enter().append("path")
  .filter(function(d) { return d.properties.type != null ? this : null; })
  .attr("class", "symbol")
  .attr("d", path.pointRadius(function(d) { return radius(d.properties.frequency * 50000); }))
  .style("fill", function(d) { return color(d.properties.type); });;

目前,过滤器设置为捕获所有点:

.filter(function(d) { return d.properties.type != null ? this : null; })

我希望用户能够更改此设置。

干杯

【问题讨论】:

    标签: javascript html d3.js


    【解决方案1】:

    这样的事情应该可以工作。为您的复选框添加一个 value 属性,以便您知道它们所指的内容。

    d3.selectAll(".filter_button").on("change", function() {
      var type = this.value, 
      // I *think* "inline" is the default.
      display = this.checked ? "inline" : "none";
    
      svg.selectAll(".symbol")
        .filter(function(d) { return d.properties.type === type; })
        .attr("display", display);
    });
    

    【讨论】:

    • 太棒了。谢谢。选中框时就像一个魅力,但取消选中并不会删除这些点。关于为什么会这样的任何想法?
    • 我有一个类似的问题:(stackoverflow.com/questions/24710672/…)。我尝试使用此处提供的代码解决我的问题,但我做不到。我很困惑,我不知道应该在我的代码中的哪里添加提供的解决方案。如果您能帮助我,我将不胜感激。
    • @Andrew Kirkegaard 如果您想更改属性(例如颜色)而不是完全删除点怎么办?我在同样的问题上苦苦挣扎,上面的答案救了我!但我想更改剩余未选中选项的属性,而不是删除它们。
    • 您可以更改另一个属性,而不是使用 .attr 函数更改“显示”属性。如果是 css 属性,请改用 style 函数:github.com/d3/d3-selection/blob/master/…
    猜你喜欢
    • 2020-02-13
    • 1970-01-01
    • 2023-04-05
    • 2013-06-06
    • 2017-01-17
    • 1970-01-01
    • 2011-06-28
    • 2023-03-28
    • 1970-01-01
    相关资源
    最近更新 更多