我如何在D3中使用下拉按钮触发鼠标悬停事件?

How can I trigger a mouseover event using a dropdown in D3?

本文关键字:按钮 鼠标 悬停 事件 D3      更新时间:2023-09-26

我正在使用D3.js构建折线图,我希望用户能够使用下拉菜单来突出显示其邮政编码的值。当用户将鼠标悬停在一行上时,我已经用鼠标悬停事件来实现了这一点。

我已经尝试设置鼠标悬停和鼠标出事件来调用"onmouseover"函数,如下所示:

series.selectAll(".hover")
 .on("mouseover", function(d,i) {
   d3.selectAll(".line")
     .style("opacity", 0.82)
     .filter(function(p) { return p.zipcode == d.zipcode; })
     .style("opacity", 1)
     .style("stroke-width", 2)
     .style("stroke", function(d,i) { return color2(i); });
   d3.selectAll(".series text")
     .style("opacity", 0)
     .filter(function(p) { return p.zipcode == d.zipcode; })
     .style("opacity", 1)
     .on("mouseover", onmouseover)
     .on("mouseout", onmouseout);

我也有我的"onmouseover"功能,是由下拉菜单激活:

function onmouseover(d,i){
    d3.selectAll(".line")
      .style("opacity", 0.82)
      .filter(function(p) { return p.name == d.name; })
      .style("opacity", 1)
      .style("stroke-width", 2)
      .style("stroke", function(d,i) { return color2(i); })
     d3.selectAll(".series text")
      .style("opacity", 0)
      .filter(function(p) { return p.name == d.name; })
      .style("opacity", 1);}})        

当使用下拉菜单时,我尝试激活它:

$("#dropdownselect").change(ziphandler)
   function ziphandler(){
   var key = $(this)
          .children(":selected")
          .val();
  onmouseover({id : key});
}

理想的结果是,用户可以将鼠标悬停在一行上查看新样式,并通过在下拉菜单中选择邮政编码来突出显示该行。

编辑:代码在这里看到的行动:http://bl.ocks.org/cminshew/31581ca3e55fbf67862a

你的代码有几个问题:

  • 你没有包含JQuery
  • 下拉选择器的ID是zipselected,而不是dropdownselect
  • ziphandleronmouseover函数在不同的作用域中声明。特别是,你不能从ziphandler调用onmouseover
  • 在你的onmouseover函数中,你引用了一个不存在的.name属性。

我想你应该调用$(this).onmouseover({id : key});