我正在使用d3.js绘制几个条形图。绘图完成后,我想更改所选条形的颜色,但它总是失败。似乎drawBars()
和updateColor()
同时被调用。
function redraw(data){
drawBars(data);
updateColor();
}
如何在drawBars()
被调用之前确保updateColor()
完成?
首先,我在drawBar的末尾添加了更新功能代码,但它没有工作。后来,我把它移到了重绘功能的末尾,它也没有用。 这是具体的代码:
function drawBar(drawData){
var w = 1060,h = 600;
d3.selectAll("svg").remove();
var svg = d3.select("#chart").append("svg").attr("width",w).attr("height",h);
uni.forEach(function(element,index,array){
$('.uni').css("top",function(index){
return (index + 1) * 18 + 28;
});
});
$(".rankingheader").css("display","block");
$("#switch input").prop("checked", false);
starData = drawData;
revCountData = drawData;
sentData = drawData;
bizCountData = drawData;
drawAxis(drawData);
drawStar(starData);
drawRev(revCountData);
drawSent(sentData);
drawBiz(bizCountData);
drawLineA(starData);
drawLineB(starData,revCountData);
drawLineC(revCountData,sentData);
drawLineD(sentData,bizCountData);
// cart is a list which stored the id selected by user
if(cart.length > 0){
cart.forEach(function(element,index,array){
d3.select("#starHoverLine" + element).attr("visibility","visible");
d3.select("#starHintText" + element).attr("visibility","visible");
d3.select("#revHoverLine" + element).attr("visibility","visible");
d3.select("#revHintText" + element).attr("visibility","visible");
d3.select("#sentHoverLine" + element).attr("visibility","visible");
d3.select("#sentHintText" + element).attr("visibility","visible");
d3.select("#bizHoverLine" + element).attr("visibility","visible");
d3.select("#bizHintText" + element).attr("visibility","visible");
d3.select("#lineA" + element).style("stroke","red");
d3.select("#lineB" + element).style("stroke","red");
d3.select("#lineC" + element).style("stroke","red");
d3.select("#lineD" + element).style("stroke","red");
d3.select("#starBar" + element).attr("fill","red");
d3.select("#revBar" + element).attr("fill","red");
d3.select("#sentBar" + element).attr("fill","red");
d3.select("#bizBar" + element).attr("fill","red");
});
}
}
答案 0 :(得分:0)
您的两个功能不会同时调用;他们被称为一个接一个。如果它们似乎同时被调用,则会发生以下两种情况之一:
drawBars
开始异步完成的内容(如ajax请求或动画),或
drawBars
正在进行浏览器未立即显示的更改,并且您希望暂时回退到浏览器以允许它在调用updateColor
之前显示(呈现)这些更改
如果它是#1,那么你需要查看drawBars
开始知道如何知道它何时完成的异步操作的文档。通常这是回调或承诺。根据它的不同,您需要将updateColors
作为参数传递给drawBars
(这样您就可以从异步回调中调用它),或让drawBars
返回承诺并使用promise的then
方法将updateColors
添加到履行承诺时要调用的函数队列。
如果它是#2,那就更简单了:
setTimeout(updateColors, 100); // Wait 100ms (1/10th second) and call `updateColors`