我有以下jQuery接受来自AJAX请求的响应来构建一个表,但是在它下面的追加之后每个似乎都被触发了,我如何确保在每个表完成之前表不会被关闭。
$.ajax({
type: "POST",
url: "api/getFirmTabletsDetails.php",
data: "id=" + firmID,
cache: false,
dataType: "json",
success: function(result)
{
var tabletArea = modal.find('#tablet-body');
tabletArea.html("");
tabletArea.append
(
'<div class="col-lg-12">
<table class="table table-hover table-striped"><thead>
<tr><th>Name</th><th>Status</th><th>Address</th></tr>
</thead><tbody>'
);
if (result.success = 1)
{
$.each(result.request, function( index, value )
{
var address = value.Street + "<br>" + value.Street2 + "<br>"
+ value.Town + "<br>" + value.County + "<br>"
+ value.Postcode;
tabletArea.append('<tr><td>'+value.Name+
'</td><td>'+value.Status+'</td><td>'+address+'</td></tr>');
});
}else{
alert(result.error);
}
tabletArea.append('</tbody></table></div></div>');
}
});
输出:
<html>
<head>
<title></title>
</head>
<body>
<div class="modal-body" id="tablet-body">
<div class="col-lg-12">
<table class="table table-hover table-striped">
<thead>
<tr>
<th>Name</th>
<th>Status</th>
<th>Address</th>
</tr>
</thead>
</table>
</div>
<table>
<tr>
<td>...</td>
<td>...</td>
<td>...
<br />...
<br />...
<br />...
<br />...</td>
</tr>
<tr>
<td>...</td>
<td>...</td>
<td>...
<br />...
<br />...
<br />...
<br />...</td>
</tr>
</table>
</div>
</body>
</html>
答案 0 :(得分:2)
您使用
append
方法的方式不正确。
正如您可以在官方文档中看到的那样,append( content )
采用的参数可以是DOM element, text node, array of elements and text nodes, HTML string, or jQuery object to insert at the end of each element in the set of matched elements.
您在这里做的是重复传递一些字符串。您应该为要追加的元素传递完整的htmlString。如果你想采取类似于你已经做过的方法,你可以保留一个字符串并继续添加元素。完成后,您可以将字符串传递给append(content)
方法一次。检查下面给出的代码:
$.ajax({
type: "POST",
url: "api/getFirmTabletsDetails.php",
data: "id=" + firmID,
cache: false,
dataType: "json",
success: function(result){
var tabletArea = modal.find('#tablet-body');
tabletArea.html("");
var htmlString = "";
htmlString += '<div class="col-lg-12"><table class="table table-hover table-striped"><thead><tr><th>Name</th><th>Status</th><th>Address</th></tr></thead><tbody>';
if (result.success = 1){
$.each(result.request, function( index, value ) {
var address = value.Street + "<br>" + value.Street2 + "<br>" + value.Town + "<br>" + value.County + "<br>" + value.Postcode;
htmlString += '<tr><td>'+value.Name+'</td><td>'+value.Status+'</td><td>'+address+'</td></tr>';
});
}else{
alert(result.error);
}
htmlString += '</tbody></table></div></div>';
tabletArea.append( htmlString );
}
});