按钮点击,
中的映射无法在淘汰赛中工作我在淘汰赛中使用了映射,同时在点击按钮未正确更改时更改输入文本值。 单击加载用户数据按钮后需要更改名称输入文本的值
这是我的代码,
<div class='sample'>
<p>Load: <input type="button" value="Load User Data" data-bind="click: loadUserData" /></p>
<p>Name: <input data-bind='value: firstName' /></p>
<p>Save: <input type="button" value="Save User Data" data-bind="click: saveUserData" /></p>
</div>
<script>
$(document).ready(function () {
var viewModel = {};
viewModel.firstName = 'Knockout JS';
viewModel.loadUserData = function () {
$.getJSON("/data.json", function (data) {
// update the data in existing ViewModel.
viewModel.firstName = data.name;
ko.mapping.fromJS(data, viewModel);
});
};
viewModel.saveUserData = function () {
// Convert the viewModel into JSON.
var data_to_send = { userData: ko.toJSON(viewModel) };
// Send that JOSN data to server.
$.post("WebService.asmx/updateData", data_to_send, function (data) {
alert("Your data has been posted to the server!");
});
};
ko.applyBindings(viewModel);
});
</script>
我有什么不对吗?
答案 0 :(得分:1)
为了更新UI,您需要创建firstName observable
。
然后,当您想要修改一个可观察值时,您需要将其视为一个函数并将新值作为参数传递,如firstName('newValue')
请参阅链接here以获取更多信息和示例如下:
var masterVM = (function () {
var self = this;
self.firstName = ko.observable("Knockout JS");
self.loadUserData = function() {
var currentName = self.firstName();
self.firstName(currentName + "Updated");
}
})();
ko.applyBindings(masterVM);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<p>Load: <input type="button" value="Load User Data" data-bind="click: loadUserData" /></p>
<p>Name: <input data-bind='value: firstName' /></p>