我是一般的编程和Knockout.js的新手,因此我要求的是非常基本的。我正在尝试使用Knockout.js创建一个表单。就像练习一样,我想创建这个页面,每当有人更新字段并单击提交时,它会将其映射到JSON并提醒它如何看起来像JSON。通过这段代码,我有它正确绑定,但它不会更新JSON文件。怎么了?
以下是我的代码:
var User = {
Email : ko.observable(''),
Password : ko.observable(''),
FullName : ko.observable('')
};
ko.applyBindings(User);
var JsonData=ko.toJSON(User);
function submit(){
alert (JsonData)
}
和我的HTML:
<html>
<head>
<title> Test Knockout</title>
</head>
<script src="knockout-3.1.0.js" type="text/Javascript"></script>
<script src="js/jquery-2.1.0.min.js" type="text/Javascript"></script>
<link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
<body>
<form data-bind="submit: submit" data-bind="foreach:friends">
<!--==Email==-->
<div class="form-group">
<input type="Email" class="form-control input-lg" placeholder="*Email" data- bind="value:Email">
<input type="password" class="form-control input-lg" placeholder="*Password" data-bind="value:Password">
<input type="text" name="FullName" id="FullName" class="form-control input-lg" placeholder="Full Name" data-bind="value:FullName">
<button type="submit">Submit</button>
<p data-bind="text:Email"></p>
<p data-bind="text:Password"></p>
<p data-bind="text:FullName"></p>
</div>
</form>
<script src="Jav.js" type="text/Javascript"></script>
<script src="knockout.mapping-latest.js" type="text/Javascript"></script>
</body>
</html>
由于
答案 0 :(得分:2)
这是您的代码的工作小提琴:http://jsfiddle.net/dwqZw/1/
HTML:
<form data-bind="submit: submit">
<!--==Email==-->
<div class="form-group">
<input type="Email" class="form-control input-lg" placeholder="*Email" data-bind="value: user.Email, valueUpdate: 'input'" />
<input type="password" class="form-control input-lg" placeholder="*Password" data-bind="value: user.Password, valueUpdate: 'input'" />
<input type="text" name="FullName" id="FullName" class="form-control input-lg" placeholder="Full Name" data-bind="value: user.FullName, valueUpdate: 'input'" />
<button type="button" data-bind="click: submit">Submit</button>
<p data-bind="text: user.Email"></p>
<p data-bind="text: user.Password"></p>
<p data-bind="text: user.FullName"></p>
</div>
</form>
的javascript:
var user = {
Email: ko.observable(''),
Password: ko.observable(''),
FullName: ko.observable(''),
};
function submit() {
var json = ko.toJSON(user);
alert(json);
}
var viewModel = {
user: user,
submit: submit
};
ko.applyBindings(viewModel);