我正在尝试从数据库中提取数据并显示在表格中的 MVC 示例(使用 Knockout JS)。我想对行应用深色条纹和浅色条纹。条纹仅在我应用 CSS 时显示,在调用 ko.applyBindings(viewModel) 之后立即显示,而不显示在其他任何地方。
请帮助我了解这里发生了什么。看起来像是与 HTML 呈现相关的基础知识。
伪代码
Ajax_call()
{
Fetch data from MVC controller(Web API)
Call knockout to construct table
Apply stripes. Stripes appear and stay.
}
NavigateToNextPage()
{
Call strip() from here, stripes appear JUST momentarily.
It is so fast that I can see it ONLY when I put a break-point inside
controller. It seems when Knockout draws the NEXT page, it removes
stripes.
Ajax_call();
Same problem if I call from here.
}
完整代码
abc.js
=======
function getData()
{
$.ajax(
{
type: "get",
url: "/api/CollaborationSpaces/Page/" + CurrentPage,
cache: false,
context: this,
dataType: "json",
success: function (data)
{
var viewModel = ko.mapping.fromJS(data);
ko.applyBindings(viewModel);
//**IMPORTANT** If I call stripe() from here, I see stripes.
}
});
}
var CurrentPage = 1
function stripe()
{
$("tr:even").addClass("even");
$("tr:odd").addClass("odd");
}
function Move(pages)
{
CurrentPage = CurrentPage + pages;
//**IMPORTANT**
//If I call strip() from here, stripes appear momentarily.
//It is so fast, I can see it ONLY when I put break-point inside
//controller. It seems when Knockout draws the NEXT page, it removes
//stripes
getData();
//IMPORTANT this stripe has no effect.
stripe();
}
CSS
===
.odd {
background-color: #ebeced;
}
.even {
background-color: #99acb9;
}
Razor
=====
<h2>@ViewBag.Title</h2>
<p><span id="ItemsFound" data-bind="text: NumberOfResults"></span> Records Found</p>
<p>Page <span id="PageNumber" data-bind="text: CurrentPage"></span></p>
<br />
<table data-bind="template: {name: 'CollaborationSpaceTemplate', foreach:PersonInfoResults}" class="grid">
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
</tr>
</thead>
<tfoot>
<tr>
<td colspan=2 class="Pager">
<span id="back" onclick="Move(-1)">< Back</span>
<span id="next" onclick="Move(1)">Next ></span>
</td>
</tr>
</tfoot>
</table>
<div id="LoadingDiv">Loading. . .</div>
<script id="CollaborationSpaceTemplate" type="text/html">
<tr>
<td data-bind="text: FirstName"></td>
<td data-bind="text: LastName"></td>
</tr>
</script>
最佳答案
success: function (data) {
var viewModel = ko.mapping.fromJS(data);
ko.applyBindings(viewModel);
//**IMPORTANT** If I call stripe() from here, I see stripes.
}
是的,您应该从回调中调用 stripe()
(在 applyBindings
之后),以便您尝试添加类的元素出现在标记中。
关于javascript - CSS 无法对 Knockout 绘制的表格应用 dark-stripe 和 light-stripe,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30268522/