2017-02-28 41 views
2

我有一个美国地图,其中包含可选择的县,点击时将其背景更改为红色。我想要发生的是,当用户点击另一个县时,它会取消选择当前县,然后只选择新县。目前,当点击县级时,它会更改类背景为红色的类,但是当您单击另一个县时,它们都是红色的。如何在使用javascript点击另一课程时取消选择课程

这里就是我绘制地图和变化类点击时的代码:

 //DRAW MAP 
     d3.json("js/map.json", function(error, mapData){ 
      if (error) throw error; 
      //draw counties 
      edit.map.append("g") 
       .selectAll("path") 
       .data(topojson.feature(mapData, mapData.objects.counties).features) 
       .enter().append("path") 
       .attr("class", "counties") 
       .attr("d", edit.path) 
       .on("click", function(d){ 
        sFips = d.properties.STATEFP; 
        cFips = d.properties.COUNTYFP; 

        //display values in text boxes 
        $("#locationCountySelect").val(cFips); 
        $("#locationStateSelect").val(sFips); 

        //change clicked county class name     
        if (this.className.baseVal == "counties") { 
         this.className.baseVal = "selectedCounty"; 
         //send new county to db 
        } else { 
         this.className.baseVal = "counties"; 
        } 
       }); 
     }); 

同样,我怎么能只在某一时刻选择一个县?

回答

2

为此,我建议你沟渠jQuery赞成D3。下面两行的click听众将做的工作:

d3.select(".selectedCounty").attr("class", "counties"); 
d3.select(this).attr("class", "selectedCounty"); 

第一条语句选择具有.selectedCounty类的元素,并将class属性counties代替。第二个选择单击的元素并将其类设置为selectedCounty

这也可能是值得考虑的,以保持当前选定的元素的引用在外部范围的变量不具有对每一次点击重新选择:

var selectedCounty = d3.select(".selectedCounty"); 

edit.map.append("g") 
// ... 
    .on("click", function(d) { 
    selectedCounty.attr("class", "counties"); 
    selectedCounty = d3.select(this).attr("class", "selectedCounty"); 
    } 

按照要求由特顿编码器的comment有可能需要切换类而不是仅仅替换它。使用selection.attr("class", "selectedCounty")将设置class属性的值,从而替换元素上设置的任何其他类。虽然您可以通过此功能将空格分隔列表传递给属性,但切换元素上特定类的最简单方法是使用selection.classed()。该函数的第二个参数是一个布尔值,用于确定该类是应该分配给该元素还是将其从该元素中移除,同时保留所有其他类不变。上面的代码可以被重写为:

var selectedCounty = d3.select(".selectedCounty"); 

edit.map.append("g") 
// ... 
    .on("click", function(d) { 
    selectedCounty.classed("selectedCounty", false); 
    selectedCounty = d3.select(this).classed("selectedCounty", true); 
    } 
+0

太棒了,谢谢!第一个像魅力一样工作。第二个没有工作。 – lostInTheTetons

+1

请给第二个尝试。我编辑它以避免第一次点击时出现空值。我更喜欢第二种解决方案,因为它比第一种更好。 – altocumulus

+0

第二人也像魅力一样工作,谢谢! – lostInTheTetons