1
我試圖在計算名和姓時試圖推送多個數據(名字和姓氏),並嘗試將數據推送到同一個數組中我被拋出錯誤。以下是我的代碼。將可觀察數據和計算數據推送到可觀察數組
視圖模型:
var viewModel = function() {
var self = this;
self.gameofthrones = ko.observableArray ([
{firstname: 'Jon', lastname: 'Snow'},
{firstname: 'Robb', lastname: 'Stark'}
]);
self.firstname = ko.observable('');
self.lastname = ko.observable('');
for (var i=0; i<self.gameofthrones().length; i++) {
self.gameofthrones()[i].fullname = ko.computed (function() {
return self.gameofthrones()[i].firstname+" "+self.gameofthrones()[i].lastname;
})
};
$('#classic').click(function() {
self.gameofthrones.push(
{firstname: $('#fn').val(), lastname: $('#pr').val()}
);
});
}
ko.applyBindings(new viewModel());
HTML瀏覽:
<form class="" action="index.html" method="post">
<input type="text" name="name" data-bind="value: firstname" id="fn">
<input type="text" name="name" data-bind="value: lastname" id="pr">
<button id="classic" type="button" name="Submit">Submit</button>
</form>
<div data-bind="foreach: gameofthrones">
Firstname: <span data-bind="text: firstname"></span><br>
LastName: <span data-bind="text: lastname"></span><br>
Fullname: <span data-bind="text: fullname"></span><br><br>
</div>
我是新來的淘汰賽JS和我停留在這一點上是有辦法來顯示觀察到的陣列計算的名字和姓氏。 感謝您提前幫忙。