我不明白为什么用于设置元素属性的d3方法失败(在这段代码中),而传统的JS方法有效。(当用户单击HTML按钮更改绘制的数据时,我正在尝试更新叶绿体颜色,所有这些数据都来自相同的JSON。)
HTML很简单:
<div id="buttons">
<button id="party">Parties</button>
<button id="tenure">Tenure</button>
</div>下面是两行并排的相关JS。当我在Chrome中运行它时,我得到"Object # has no method 'attr'":
var paths = svg.selectAll("path");
var plot = {
"mode": "party",
"redraw": function() {
var e = e || window.event;
var targ = e.target || e.srcElement;
if (targ.nodeType == 3) targ = targ.parentNode;
switch (targ.id) {
case "party":
// some code in here
break;
case "tenure":
paths.each(function(d,i) {
this.setAttribute("class",""); // Same question here actually
if (d.In_Office_Full_Date) {//此行错误:
this.attr("style", "fill: " + t_scale(getJSDateFromExcel(d.In_Office_Full_Date).getFullYear()));// ...但是下面这行行得通:
this.setAttribute("style", "fill: " + t_scale(getJSDateFromExcel(d.In_Office_Full_Date).getFullYear()));
}
else
this.setAttribute("style", "fill: #111"); // Neutral colour
});
break;
default:
console.log("Unknown event trigger in redraw()");
}
}
}
var t_scale = d3.scale.linear()
.domain([1973,2013])
.range(['red','white']);
d3.select("body").selectAll("#buttons button")
.on("click",plot.redraw);希望你能帮上忙!
发布于 2014-03-10 13:06:47
问题出在您在each(function(d, i) { ... })中调用this方法的方式。
您的方向是正确的:this指的是您正在修改的纯html元素。但是,您希望调用的attr函数是d3选择的方法,而不是html元素的方法。因此,您需要将this包装在d3选择中:
paths.each(function(d,i) {
d3.select(this)
.attr("class","");
});调用setAttribute是因为它是普通html元素的一种方法,但显然d3的attr更健壮。
但话虽如此,要实现您正在做的事情,更常用的方法是:
paths
.attr("class", "")
.style("fill", function(d, i) {
if (d.In_Office_Full_Date) {
return t_scale(getJSDateFromExcel(d.In_Office_Full_Date).getFullYear());
}
return "#111";
});https://stackoverflow.com/questions/22291761
复制相似问题