【问题标题】:D3.JS Click Event problem, using a svg mapD3.JS点击事件问题,使用svg map
【发布时间】:2021-12-24 06:55:45
【问题描述】:

您好,我是 D3 库的新手,当我单击国家/地区时,我不知道如何使单击事件起作用,我知道“d”变量包含国家/地区信息,但如何我得到它来控制台登录点击。我尝试了几种方法,但无法弄清楚。任何帮助表示赞赏

   const svg = d3.select("svg"),
           width = +svg.attr("width"),
           height = +svg.attr("height");

   // Map and projection
   const projection = d3.geoNaturalEarth1()
           .scale(width / 1.5 ) // Lower the num closer the zoom
           .translate([200, 700])  // (Horizontal, Vertical)

   // Load external data and boot
   d3.json("https://raw.githubusercontent.com/holtzy/D3-graph-gallery/master/DATA/world.geojson").then( function(data) {

     // Draw the map
     svg.append("g")
             .selectAll("path")
             .data(data.features)
             .join("path")
             .attr("fill", "#348C31") // Color Of Country
             .attr("d", d3.geoPath().projection(projection))
             .style("stroke", "white")// Border Lines
             .append("title")
                .text(d => console.log(d))
       //Want to run on click of country,
   })

   const $countyPaths = svg.append("g")
   .selectAll("path")
   .data(data.features)
   .join("path")

   $countyPaths
       .attr("fill", d => color(data.get(d.id)))
       .attr("d", path)
       .append("title")
   
   $countyPaths.on('click',d=>console.log(d.id))

   function buttonClick() {
       window.alert("Boom");
   }



 </script>

【问题讨论】:

    标签: javascript d3.js


    【解决方案1】:

    d3 提供.on(event, fx(event, d)) 方法来处理事件。 要记录国家/地区,您可以执行以下操作:

    svg.append("g")
             .selectAll("path")
             .data(data.features)
             .join("path")
             .attr("fill", "#348C31") // Color Of Country
             .attr("d", d3.geoPath().projection(projection))
             .style("stroke", "white")// Border Lines
             .on("click", (_, d) => console.log(d))
    

    请注意,来自事件监听器的函数将接收的第一件事是事件信息,第二件事是数据

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-10-15
      • 1970-01-01
      • 2014-01-16
      • 1970-01-01
      • 1970-01-01
      • 2016-12-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多