我想创建一个包含json数据的表,我应该修改我的jquery代码,以便能够创建包含数据或其他内容的行(仅修改我的json,css?...)
我需要使用我的数据水平创建一个表,此时我将<th>
标记与css作为一行显示为内联,但使用json导入的数据垂直放在一列中。
Jquery的:
$(document).ready(function() {
$.ajax({
url: 'weather.json',
type: 'GET',
dataType: 'json', // Returns JSON
success: function(response) {
var sTxt = '';
$.each(response, function(index, weatherElement) {
sTxt += '<tr><td>' + weatherElement.city+'</td></tr>';
sTxt += '<tr><td>' + weatherElement.current_condition+'</td></tr>';
sTxt += '<tr><td>' + weatherElement.temperature+'</td></tr>';
sTxt += '<tr><td>' + weatherElement.wind_speed+'</td></tr>';
sTxt += '<tr><td>' + weatherElement.wind_direction+'</td></tr>';
sTxt += '<tr><td>' + weatherElement.wind_chill_factor+'</td></tr>';
});
$('#weatherlist').append(sTxt);
},
error: function() {
$('#info').html('<p>An error has occurred</p>');
}
});
});
HTML:
<!DOCTYPE html>
<html>
<head>
<title>Ajax and json Data</title>
<meta charset="UTF-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="weather.js" type="text/javascript"></script>
<link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>
<header>
<h1>British and Irish Counties - Weather Data</h1>
</header>
<section>
<table id="weatherlist">
<tr>
<th>City</th>
<th>Conditions</th>
<th>Temperature</th>
<th>Wind Speed</th>
<th>Wind Direction</th>
<th>Wind Chill Factor</th>
</tr>
</table>
<div id="updatemessage"></div>
<p id="info"></p>
</section>
<footer>
</footer>
</body>
</html>
答案 0 :(得分:5)
您的表格行格式不正确。您应该将所有td元素包装在一个tr元素中。
改变这个:
sTxt += '<tr><td>' + weatherElement.city+'</td></tr>';
sTxt += '<tr><td>' + weatherElement.current_condition+'</td></tr>';
sTxt += '<tr><td>' + weatherElement.temperature+'</td></tr>';
sTxt += '<tr><td>' + weatherElement.wind_speed+'</td></tr>';
sTxt += '<tr><td>' + weatherElement.wind_direction+'</td></tr>';
sTxt += '<tr><td>' + weatherElement.wind_chill_factor+'</td></tr>';
对此:
sTxt += '<tr>';
sTxt += '<td>' + weatherElement.city+'</td>';
sTxt += '<td>' + weatherElement.current_condition+'</td>';
sTxt += '<td>' + weatherElement.temperature+'</td>';
sTxt += '<td>' + weatherElement.wind_speed+'</td>';
sTxt += '<td>' + weatherElement.wind_direction+'</td>';
sTxt += '<td>' + weatherElement.wind_chill_factor+'</td>';
sTxt += '</tr>';