我正在使用Plotly.js来渲染一些股票数据。我希望总共有5个图表而不重复自己。所以我创建了一个数组,给出了我要调用的每个链接的键和值对。
var links = {
'microsoft':'https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=MSFT&apikey=APIKEY&datatype=csv',
'apple': 'https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=MSFT&apikey=APIKEY&datatype=csv',
'tesla':'https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=MSFT&apikey=APIKEY&datatype=csv',
'amazon':'https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=MSFT&apikey=APIKEY&datatype=csv',
'facebook':'https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=MSFT&apikey=APIKEY&datatype=csv'
};
从那里我使用for循环来循环遍历每个键值对与我的 情节之间的功能。
for (var key in links) {
//url of the data I am passing
Plotly.d3.csv(links[key], function(err, rows){
function unpack(rows, key) {
return rows.map(function(row) {
return row[key];
});
}
var trace = {
x: unpack(rows, 'timestamp'),
close: unpack(rows, 'open'),
high: unpack(rows, 'high'),
low: unpack(rows, 'low'),
open: unpack(rows, 'close'),
// cutomise colors
increasing: {line: {color: 'black'}},
decreasing: {line: {color: 'red'}},
type: 'candlestick',
xaxis: 'x',
yaxis: 'y'
};
var data = [trace];
var layout = {
dragmode: 'zoom',
showlegend: false,
xaxis: {
rangeslider: {
visible: false
}
}
};
//this key is the value of the id of the html element
Plotly.plot(key, data, layout);
});;
}
此函数运行正常,但只打印DOM中的第一对。我想要所有5.我不知道我做错了什么。
更新:
以下是我尝试将这些项目呈现的html元素。
<div class="container-fluid" id="home__page">
<div class="row ">
<div class="col-6">
<div id="microsoft">
</div>
</div>
</div>
<div class="row ">
<div class="col">
<div id="apple">
</div>
</div>
</div>
<div class="row ">
<div class="col">
<div id="tesla">
</div>
</div>
</div>
<div class="row ">
<div class="col">
<div id="amazon">
</div>
</div>
</div>
<div class="row ">
<div class="col">
<div id="facebook">
</div>
</div>
</div>
</div>
答案 0 :(得分:1)
我之前从未使用过暴力,我怀疑有2件事,要么是固定的id /容器被给予和覆盖,要么是密钥不断重新分配。你会尝试这个,否则我会删除答案:
for (var key in links) {
(function(key,links){
//url of the data I am passing
Plotly.d3.csv(links[key], function(err, rows){
function unpack(rows, key) {
return rows.map(function(row) {
return row[key];
});
}
var trace = {
x: unpack(rows, 'timestamp'),
close: unpack(rows, 'open'),
high: unpack(rows, 'high'),
low: unpack(rows, 'low'),
open: unpack(rows, 'close'),
// cutomise colors
increasing: {line: {color: 'black'}},
decreasing: {line: {color: 'red'}},
type: 'candlestick',
xaxis: 'x',
yaxis: 'y'
};
var data = [trace];
var layout = {
dragmode: 'zoom',
showlegend: false,
xaxis: {
rangeslider: {
visible: false
}
}
};
//this key is the value of the id of the html element
Plotly.plot(key, data, layout);
});;
})(key,links)
}