我需要在首页加载时向用户显示最新评论,就像添加新评论之后一样,新评论已成功添加到可观察数组,但是我无法显示最新评论,我正在尝试此代码,但确实如此不行。
我的代码附在JsFiddle中
function Comment(NoteText, CreateDate) {
this.commentText = ko.observable(NoteText);
this.createDate = ko.observable(CreateDate);
}
function CommentList() {
var nm = this;
nm.newComment = ko.observable();
nm.allComments = ko.observableArray([{ commentText: 'Hellow world', createDate: 'some date' }]);
nm.AddNewComment = function () {
nm.allComments.push(new Comment(this.newComment(), Date()));
this.newComment('');
}
ko.applyBindings(nm, document.getElementById("comments"));
}
var comments = new CommentList();
$("#allcomments").hide();
$("#btnViewAll").click(function () {
$("#allcomments").show();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<div id="comments">
<input type="text" data-bind="value:newComment" /><button data-bind="click: AddNewComment">Add New Comment</button><br />
<hr />
Last Comment: <strong> <span data-bind="text: allComments[allComments.length-1]"></span> </strong><button id="btnViewAll">View ALL</button>
<br />
<div id="allcomments">
<h2>All Comments</h2>
<table>
<thead>
<tr>
<td>Comment Text</td>
<td>Date</td>
</tr>
</thead>
<tbody data-bind="foreach: allComments">
<tr>
<td><span data-bind="text: commentText"></span></td>
<td><span data-bind="text: createDate"></span></td>
</tr>
</tbody>
</table>
</div>
</div>
allComments
是一个可观察的数组,因此您需要使用括号来获取表达式所包含的数组
"text: allComments()[allComments().length-1]"
为了清楚起见,最好是创建一个计算名称lastComment
并在绑定中使用该名称。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句