如何给输出内容:名称:...,描述:...,主温度:...而不是:名称:...,名称:...,名称:...,说明...,说明:..
for (var i = 0; i < 3; i++) {
$('#name').append('<b>Name:</b><ul>' + `<li>${name[i]}</li>` + '</ul>');
$('#main_temp').append('<b>Main Temp: </b><ul>' + `<li>${mainTemp[i]}</li>` + '</ul>');
$('#weather_description').append('<b>Weather Description:</b><ul>' + `<li>${description[i]}</li>` + '</ul>');
}
输出:
Name:
Vancouver
Name:
Vancouver
Name:
Vancouver
Weather Description:
light rain
Weather Description:
light rain
Weather Description:
clear sky
Main Temp:
289.917
Main Temp:
286.551
Main Temp:
285.244
答案 0 :(得分:0)
您可能正在寻找这样的东西:
JS
var text = '';
for (var i = 0; i < 3; i++) {
text= '';
text = '<ul>' +
`<li><b>Name: </b>${name[i]}</li>` +
`<li><b>Main Temp: </b>${mainTemp[i]}</li>` +
`<li><b>Weather Description: </b>${description[i]}</li>` +
'</ul>';
$('#container').append(text);
}
HTML
<div id="container">
</div>
问题在于,您总是将其追加到同一元素上。
答案 1 :(得分:0)
您可以使用模板从逻辑中提取html,并更好地定义输出应存在的分组。
var names = [ 'Vancouver', 'Vancouver', 'Vancouver' ];
var description = [ 'light rain', 'light rain', 'light rain' ];
var mainTemp = [ 289.917, 286.551, 285.244 ];
var template = document.querySelector('#outputTemplate').innerHTML;
var $output = $('#output');
for (var i = 0; i < 3; i++) {
let $template = $(template);
$template.find('.name').text(names[i]);
$template.find('.description').text(description[i]);
$template.find('.mainTemp').text(mainTemp[i]);
$output.append($template);
}
.group {
border: 1px solid rgb(0, 0, 0);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="output">
</div>
<script type="text/html" id="outputTemplate">
<div class="group">
<label>
<b>Name:</b><ul><li class="name"></li></ul>
</label>
<label>
<b>Weather Description:</b><ul><li class="description"></li></ul>
</label>
<label>
<b>Main Temp:</b><ul><li class="mainTemp"></li></ul>
</label>
</div>
</script>