我的 HTML 代码是这样的:
...
<button class="save bookbtn mt1">More</button>
...
<div class="cruisedropd">
<div id="loading" class="loading"></div>
</div>
...
我的Javascript代码是这样的
...
$('.save').click(function () {
...
success: function (response) {
...
var elem = $parent.find('.loading').empty();
elem.append('<table class="table">\
<tbody>\
<tr>\
<th>Status</th>\
<th>Room Grade</th>\
<th>Meal</th>\
<th>Per Room.Night</th>\
<th>Cancel Policy</th>\
<th>Book It</th>\
</tr>')
for(var i=0; i<response.SearchAvailResponse.Hotel.length; i++){ //make sure to use var
elem.append('<tr>\
<td>' + Status + '</td>\
<td>' + RmGrade + '</td>\
<td>' + Meal + '</td>\
<td>' + Currency + ' ' + TotalRate + '</td>\
<td><a href="#">Cancel Policy</a></td>\
<td>\
<form action="details.html">\
<button class="bookbtn mt1" type="submit">Book</button>\
</form>\
</td>\
</tr>'); //add the new content
}
elem.append('</tbody>\
</table>')
...
}
...
}
...
View 是这样的:http://imgur.com/1OIVGGU
为什么我的css显示不正常?
有什么办法可以解决我的问题吗?
非常感谢
最佳答案
简短的回答是您不能以那种方式构建表格。
您的第一段代码附加了表格标题。然后 DOM 自动添加关闭表标记。
您的下一段代码运行一个循环来追加行。但是,该表已在上一步中创建。
所以你最终在 DOM 中得到 2 个不对齐的表。
建议将表构建为字符串,然后将该字符串附加到 div,以便 DOM 构建单个表。
更新:
此代码是对 OP 评论的回应,演示了如何使原始代码只需 3 个非常小的更改即可工作。该表首先构建为一个字符串。然后将该字符串附加到容器的 innerHTML。这样做可以防止 DOM 过早地向表格元素添加结束标记,就像原始代码中的情况一样。
现在表格标题和行对齐,这是规定的问题。
单击“运行代码片段”按钮以查看其运行情况。
function success() {
var html =('<table class="table">\
<tbody>\
<tr>\
<th>Status</th>\
<th>Room Grade</th>\
<th>Meal</th>\
<th>Per Room.Night</th>\
<th>Cancel Policy</th>\
<th>Book It</th>\
</tr>')
for(var i=0; i<10; i++){
html += ('<tr>\
<td>' + Status + '</td>\
<td>' + RmGrade + '</td>\
<td>' + Meal + '</td>\
<td>' + Currency + ' ' + TotalRate + '</td>\
<td><a href="#">Cancel Policy</a></td>\
<td>\
<form action="details.html">\
<button class="bookbtn mt1" type="submit">Book</button>\
</form>\
</td>\
</tr>');
}
html += ('</tbody>\
</table>');
$('#container').html( html );
}
// test data
var Status="OK", RmGrade=5, Meal="Yes", Currency="Euro", TotalRate="100";
success();
td,th {padding:2px; border:1px gray solid;}
th {background-color: peru; }
table {border-collapse: collapse;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<div id="container"></div>
关于javascript - 为什么我的 css 显示不规则?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35011725/