【发布时间】:2019-05-01 17:24:15
【问题描述】:
我正在使用 Javascript 和 D3.js 进行世界地图可视化。当您单击一个国家/地区时,所有其他国家/地区都会获得一个 inactiveCountry 类,它会添加一个 opacity: 0.3,它会突出显示所选国家/地区。我想要的是,当您再次单击突出显示的国家/地区时,所有其他国家/地区都失去了 inactiveCountry 类,因此他们再次拥有 opacity: 1。
以下是绘制地图并为其着色的代码:
g.selectAll("path").data(countries.features)
.enter().append("path")
.attr("d", pathGenerator)
.attr("class", "country")
.attr("id", function (d){
return d.properties.name
})
.attr("fill", function (d) {
return colorScaleWorldmap(colorValue(d))
})
.on("click", function (d) {
changeCountry(d.properties.name);
})
.append("title")
.text(function (d) {
return d.properties.name + ": " + colorValue(d);
});
如您所见,当您单击一个国家/地区时,它会运行函数changeCountry();,即:
function changeCountry(countryName) {
country = countryName;
console.log(country);
let totalCountries = document.getElementsByClassName("country");
// Remove class countryActive from previous selection
for (let i = 0; i < totalCountries.length; i++) {
if (totalCountries[i].classList.contains("countryActive")) {
totalCountries[i].classList.replace("countryActive", "countryInactive")
}
}
// Add class countryActive to selected country
let element = document.getElementById(country);
element.classList.add("countryActive");
for (let i = 0; i < totalCountries.length; i++) {
if (totalCountries[i].classList.contains("countryActive")) {
totalCountries[i].classList.remove("countryInactive")
} else {
totalCountries[i].classList.add("countryInactive")
}
}
}
我将如何添加一个交互,当您再次单击所选国家/地区时,所有国家/地区都变得可见(从而失去了countryInactive 类)?我尝试过使用 JQuery .click 和 .data 组合:
$("#" + country).click(function(){
$(this).data('clicked', true);
});
if($("#" + country).data('clicked')) {
alert('yes');
}
这段代码的问题是,一旦我至少点击了一个国家/地区,它似乎会保留true 语句,所以即使我在它处于非活动状态时点击它,我也会收到yes 警报.
【问题讨论】:
标签: javascript function d3.js click