我有问题动态地将JS分配给div然后立即修改div。
所有代码都是未更改的附件,我无法弄清楚为什么它的行为不符合预期,从代码中可以看到应该发生的事情是每个小部件应该左右定位,依此类推页面。
创建Div并分配动态名称,然后将代码放在div中,然后修改div位置。这应该有用吗?
var i = 0;
var howManyCharts = 4;
var float = ["left","right"];
var lastID = "chart" + i.toString();
document.getElementById("chart").id = lastID;
while (i < howManyCharts) {
var div = document.createElement('div').id = "charts" + i.toString();
div.innerHTML = chart("5","EURUSD");
div.style.float = float[i % 2];
i = i + 1;
};
逻辑处于while循环中。
<!DOCTYPE html>
<html>
<head>
<style>
#chart {
position: static;
border: 3px solid #73AD21;
width: 400px;
float: left;
float: top;
display: inline-block;
}
</style>
</head>
<body>
<div id="chart">
<script type="text/javascript" src="https://d33t3vvu2t2yu5.cloudfront.net/tv.js"></script>
<script type="text/javascript">
var i = 0;
var howManyCharts = 4;
var float = ["left","right"];
var lastID = "chart" + i.toString();
document.getElementById("chart").id = lastID;
while (i < howManyCharts) {
var div = document.createElement('div').id = "charts" + i.toString();
div.innerHTML = chart("5","EURUSD");
div.style.float = float[i % 2];
i = i + 1;
};
function chart(interval, symbol){
new TradingView.widget({
"width": 400,
"height": 400,
"symbol": symbol,
"interval": interval,
"timezone": "Australia/Sydney",
"theme": "Black",
"style": "1",
"locale": "en",
"toolbar_bg": "#f1f3f6",
"enable_publishing": false,
"hide_top_toolbar": true,
"allow_symbol_change": true,
"save_image": false,
"hideideas": true,
"studies": [
"RSI@tv-basicstudies"
]
});
};
</script>
</div>
</body>
上面发布的全部代码 也在这里小提琴手:http://js.do/code/multichart
答案 0 :(得分:1)
这里有一个逻辑错误:
var div = document.createElement('div').id = "charts" + i.toString();
div.innerHTML = chart("5","EURUSD");
第一行会将 id 分配给变量div
。我想你想要做的是
var div = document.createElement('div');
div.id = "charts" + i.toString();
div.innerHTML = chart("5","EURUSD");
重新布局 - 我建议不要使用花车。它们应该更多地用于允许文本环绕项目,而不是一般布局。
我建议使用flex布局,就像这样。
div {
margin: 5px;
padding: 5px;
border: solid 1px black;
}
.container {
display: flex;
flex-flow: row wrap;
}
.item {
flex: 1 0 40%; //cheap hack to account for margins
height: 50px;
}
<div class = "container">
<div class = "item">1</div>
<div class = "item">2</div>
<div class = "item">3</div>
<div class = "item">4</div>
</div>