[英]How to take value from input field and assign it to a JavaScript object in your view model?
我需要創建一個簡單的注釋框(例如像Facebook注釋),並帶有剔除js。 我是KO的新手,我嘗試進行搜索,但似乎找不到這個愚蠢問題的答案。 我會花更多的時間,但我需要快速完成功課。 這是我的HTML:
<div id="comment-input-container">
<input type="text" placeholder="comment..." data-bind="value: commentText">
<button type="submit" data-bind="click: addComment">Add comment</button>
</div> <!-- From this input I need to take the commentText and use it in the addComment function -->
<hr>
<!-- Knockout Template for showing comments -->
<div id="comment-box" data-bind="foreach: comments">
<p data-bind="text: fullName"></p>
<p data-bind="text: datePosted"></p>
<div class="commentBody">
<div class="commentContent">
<div class="commentText" data-bind="text: commentText"></div>
<div class="commentButtonsBox"></div>
</div>
</div>
</div>
這是JS:
function CommentsViewModel() {
var self = this;
self.comments = ko.observableArray([{
fullName: "Todor Atanasov",
datePosted: new Date(),
commentText: "Awesome vid guys ty."}
]);
self.addComment = function() {
self.comments.push({
fullName: "new guy",
datePosted: new Date(),
commentText: "new comment"
})
}
}
ko.applyBindings(new CommentsViewModel());
所以我應該在commentText處寫些什么:“ new comment”
嘗試這個:
function CommentsViewModel() {
var self = this;
self.newComment = ko.observable(); //add this
self.comments = ko.observableArray([{
fullName: "Todor Atanasov",
datePosted: new Date(),
commentText: "Awesome vid guys ty."}
]);
self.addComment = function() {
self.comments.push({
fullName: "new guy",
datePosted: new Date(),
commentText: self.newComment()
})
}
}
ko.applyBindings(new CommentsViewModel());
替換此html行:
<input type="text" placeholder="comment..." data-bind="value: newComment " />
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.