我在让 KO 和 jQuery Validate 插件一起工作时遇到了一些问题。
我的模型:
Parameter {
int Id;
string Name;
decimal Price;
}
还有我的 HTML+JS:
<DOCTYPE html>
<html>
<head>
<meta http-equiv='Content-Type' content='text/html;charset=utf-8'></meta>
<script type='text/javascript' src='js/jquery-1.8.3.min.js'></script>
<script type='text/javascript' src='js/jquery.validate.min.js'></script>
<script type='text/javascript' src='js/knockout-2.2.0.js'></script>
<script type='text/javascript' src='js/knockout.mapping-latest.js'></script>
</head>
<script type="text/javascript">
function AdminViewModel() {
var self = this;
self.parameters = ko.observableArray();
self.getParameters = function() {
// gets all parameters for the element with specified id (1)
$.getJSON('http://localhost:81/api/parameters/1', function(parameters){
ko.mapping.fromJS(parameters, {}, self.parameters);
});
}
self.save = function() {
alert('Submit!');
}
}
jQuery(function( $ ) {
var viewModel = new AdminViewModel();
ko.applyBindings(viewModel);
viewModel.getParameters();
$("#form-settings").validate({ submitHandler: viewModel.save });
});
</script>
<body>
<form id="form-settings" action="javascript:void(0);">
<!-- ko foreach: parameters() -->
<!--<p data-bind="foreach: parameters()">-->
Parameter <input class="required" type="text" data-bind="value: $data.Name" /><br />
Price <input class="required number" type="text" data-bind="value: $data.Price" /><br />
<!--</p>-->
<!-- /ko -->
<button type="submit">Save</button>
</form>
</body>
</html>
验证无法正常工作,有时会提交表单并在出现错误时重新加载页面,有时错误消息仅针对一个输入显示,我的代码有什么问题?