所以我试图做的是 阻止表标题<th>Username</th>
等......一旦它们已经存在就被重写到页面,或清除存在的内容在results
元素中并重写它。我尝试的任何东西似乎都没有用。我试图检查.length == 0
或< 1
或< 2
,尝试检查.get(0)
,.text("")
,似乎没有任何内容可以使用{{3} }。要么只是不断重写标题,要么根本不写它们。我希望它只添加结果而不是标题,或者最好清除结果,并在每次单击按钮时重新重写所有内容。问题是当我每次单击按钮时,我认为长度从0开始或者entryIndex回到0。
<div>
<h4>Results</h4>
<table class="table" style="white-space: nowrap" id="results">
</table>
</div>
<script>
$('#lookup').click(function (event) {
strUser = $('#userid').val();
lookfor = JSON.parse('{ "username":"' + strUser + '" }');
$.ajax({
type: "POST",
url: "/Home/FindUser",
data: lookfor,
}).done(function (data) {
var html = ""
if ($('#results').length < 2) {
html += "<tr>"
html += "<th>Username</th>"
html += "<th>Server</th>"
html += "<th>App</th>"
html += "</tr>"
}
var err = ""
$.each(data, function (entryIndex, entry) {
if (entry.ErrorMessage) {
err = "<tr>"
err += "<td>" + entry.ErrorMessage + "</td>"
err += "</tr>"
} else {
html += "<tr>"
html += "<td>" + entry.UserId + "</td>"
html += "<td>" + entry.ServerName + "</td>"
html += "<td>" + entry.AppName + "</td>"
html += "</tr>"
}
});
if (err.length > 0) {
$('#results').append($(err));
} else {
$('#results').append($(html));
}
});
});
</script>
答案 0 :(得分:1)
<div>
<h4>Results</h4>
<table class="table" style="white-space: nowrap" id="results">
</table>
</div>
<script>
$('#lookup').click(function (event) {
strUser = $('#userid').val();
lookfor = JSON.parse('{ "username":"' + strUser + '" }');
$.ajax({
type: "POST",
url: "/Home/FindUser",
data: lookfor,
}).done(function (data) {
var html = "";
var err = "";
$.each(data, function (entryIndex, entry) {
if (entryIndex == 0) {
html += "<tr>"
html += "<th>Username</th>"
html += "<th>Server</th>"
html += "<th>App</th>"
html += "</tr>"
}
if (entry.ErrorMessage) {
err = "<tr>"
err += "<td>" + entry.ErrorMessage + "</td>"
err += "</tr>"
} else {
html += "<tr>"
html += "<td>" + entry.UserId + "</td>"
html += "<td>" + entry.ServerName + "</td>"
html += "<td>" + entry.AppName + "</td>"
html += "</tr>"
}
});
if (err.length > 0) {
$('#results').append($(err));
} else {
$('#results').append($(html));
}
});
});
</script>
您可以使用每个函数对数组建立索引,因此您知道数组中的第一个项目。您可以使用索引有条件地添加标题。