我有一个问题是为不同的datetime
显示不同的内容以及foreach
绑定。
一切都运作良好,但主要问题是函数showData
和getDataByCurrentDate
我创建了一些示例代码来展示我尝试做的事情:
这是我的JavaScript代码:
var data = { "Blog": [
{
"date":"07/09/2012",
"title":"Title 1",
"content":"Text 1"
},
{
"date":"08/09/2012",
"title":"Title 2",
"content":"Text 2"
},
{
"date":"09/09/2012",
"title":"Title 3",
"content":"Text 3"
},
{
"date":"10/09/2012",
"title":"Title 4",
"content":"Text 4"
}
]
};
var current = new Date();
function formatCurrentDate() {
return ('0' + current.getDate()).slice(-2) + '/' + ('0' + (current.getMonth() + 1)).slice(-2) + '/' + current.getFullYear();
}
function getDataByCurrentDate() {
var output = [];
for(var i in data.Blog) {
if(data.Blog[i].date== formatCurrentDate()) {
output.push(data.Blog[i]);
}
}
return output;
}
function showData(data) {
var output = 'No data';
if(data.length > 0) {
for(var i in data) {
self.findDataBlog.push(data1[x]);
}
}
}
function loadData() {
var data = getDataByCurrentDate();
showData(data);
showCurrentDate();
}
function showCurrentDate() {
document.getElementById('currentDate').innerHTML = formatCurrentDate();
}
window.onload = function() {
loadData();
document.getElementById('next').onclick = function() {
current.setTime(current.getTime() + 1000*60*60*24);
loadData();
return false;
}
document.getElementById('previous').onclick = function() {
current.setTime(current.getTime() - 1000*60*60*24);
loadData();
return false;
}
}
这是body
标记:
<a href="#" id="previous"> << </a>
<span id="currentDate"></span>
<a href="#" id="next"> >> </a>
<div data-bind="foreach: findDataBlog">
<ul>
<li>
<a>
<h1><span data-bind="text: title"></span></h1>
<p>
<span data-bind="date: date"></span>
<span data-bind="text: content"></span>
</p>
</a>
</li>
</ul>
</div>
答案 0 :(得分:1)
我在这里为你创建了一个有效的jsFiddle:http://jsfiddle.net/ruslans/Y58DJ/
我所做的主要更改是在viewModel
函数中引入了淘汰showData()
变量和修正错误:
var myViewModel = {
findDataBlog = ko.observableArray();
}
ko.applyBindings(myViewModel);
...
function showData(data) {
myViewModel.findDataBlog.removeAll()
if (data.length > 0) {
for (var i in data) {
myViewModel.findDataBlog.push(data[i]);
}
}
}
修改了html:
<a href="#" id="previous"> << </a><span id="currentDate"></span>
<a href="#" id="next"> >> </a>
<br />
<span data-bind="visible: findDataBlog().length == 0">no data</span>
<div data-bind="foreach: findDataBlog, visible: findDataBlog().length > 0">
<ul>
<li> <a>
<h1><span data-bind="text: title"></span></h1>
<p>
<span data-bind="date: date"></span>
<span data-bind="text: content"></span>
</p>
</a>
</li>
</ul>
</div>
答案 1 :(得分:0)
//findDataBlog should be declare as observable array.
var findDataBlog = ko.observableArray();
// Please try with this.