我有一个圆圈,点击时颜色应变为红色。我还想调用第二个函数:"第二个单击函数"在同一次点击。
我的问题是,在这个阶段只有第二个" .on" exectues,但忽略了第一个" .on",这意味着,颜色不会改变。
var newcircle = svg.append("circle")
.data(nodes)
.attr("cx", 33)
.attr("cy", 44)
.attr("r", 33)
.style("fill", "red")
.on("click", function(){d3.select(this).style("fill", "green");})
.on("click", function(d) { "second click function" } )
如果我改变" .on"的顺序功能如下:
var newcircle = svg.append("circle")
.data(nodes)
.attr("cx", 33)
.attr("cy", 44)
.attr("r", 33)
.style("fill", "red")
.on("click", function(d) { "second click function" })
.on("click", function(){d3.select(this).style("fill", "green");})
然后它只会改变颜色,但不会执行"第二次点击功能"。
任何人都可以帮助我吗?
答案 0 :(得分:2)
您正在使用.on
函数将“click”事件绑定到en元素。通过添加事件的第二个定义,将覆盖该元素的前一个定义。
要在事件处理程序中执行另一个函数,只需在事件回调的函数体中调用它:
function resetCircleColor(ref){
// do whatever you need to here, like set the fill color to green:
// this assumes you are passing the correct reference to the circle
// you want to change as the paramter 'ref'
ref.style("fill", "red");
}
var newcircle = svg.append("circle")
.data(nodes)
.attr("cx", 33)
.attr("cy", 44)
.attr("r", 33)
.style("fill", "red")
.on("click", function(){
d3.select(this).style("fill", "green");
resetCircleColor(circleref);
});
答案 1 :(得分:2)
正如use lambdas for complex initialization, especially of const variables所解释的那样,
如果先前已为同一类型名称注册了事件侦听器 在选定的元素上,旧的侦听器在新的之前被删除 听众被添加。
但解决问题很简单;只需将所有逻辑添加到一个函数中。
{{1}}