Javascript 是“的顺序”;。关于;D3中的重要功能?
我有一个圆圈,当点击它时,它的颜色会变为红色。我还想在同一次点击中调用第二个函数:“secondclick函数” 我的问题是,在这个阶段只有第二个“.on”执行,但忽略了第一个“.on”,这意味着颜色不会改变Javascript 是“的顺序”;。关于;D3中的重要功能?,javascript,css,d3.js,svg,Javascript,Css,D3.js,Svg,我有一个圆圈,当点击它时,它的颜色会变为红色。我还想在同一次点击中调用第二个函数:“secondclick函数” 我的问题是,在这个阶段只有第二个“.on”执行,但忽略了第一个“.on”,这意味着颜色不会改变 var newcircle = svg.append("circle") .data(nodes) .attr("cx", 33) .attr("cy", 44) .attr("r", 33) .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");})
.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");})
然后它只改变颜色,而不执行“第二次单击功能”
有人能帮我吗?您正在使用
.on
功能将“单击”事件绑定到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);
});
您正在使用
.on
功能将“单击”事件绑定到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);
});
正如他解释的那样
如果事件侦听器先前已为相同的typename注册
在选定元素上,旧侦听器在新侦听器之前被删除
添加了侦听器
但解决问题很简单;只需将所有逻辑添加到一个函数中
.on("click", function(){
d3.select(this).style("fill", "green");
"second click function"
});
正如他解释的那样
如果事件侦听器先前已为相同的typename注册
在选定元素上,旧侦听器在新侦听器之前被删除
添加了侦听器
但解决问题很简单;只需将所有逻辑添加到一个函数中
.on("click", function(){
d3.select(this).style("fill", "green");
"second click function"
});
非常感谢,伙计们!一个问题:我有两个圆圈,我想当我点击圆圈a时,它会变成红色,当我点击圆圈b时,这个圆圈会变成红色,但圆圈a会回到原来的颜色…我需要一个切换功能吗?查看我的更新答案。我在click事件中调用函数
resetCircleColor
,该函数接受圆的引用作为第一个参数。您可以使用jquery或vanilla javascriptgetElementById
获取此参考,非常感谢,伙计们!一个问题:我有两个圆圈,我想当我点击圆圈a时,它会变成红色,当我点击圆圈b时,这个圆圈会变成红色,但圆圈a会回到原来的颜色…我需要一个切换功能吗?查看我的更新答案。我在click事件中调用函数resetCircleColor
,该函数接受圆的引用作为第一个参数。您可以使用jquery或vanilla javascriptgetElementById