【发布时间】:2018-05-03 13:19:00
【问题描述】:
我还是新手,所以也许我做错了什么。我有一个带有动态输入控件的 html 表单,可以由用户添加。我不知道问题是不是由无容器控制流语法引起的,但我不知道如果没有它我怎么能达到同样的结果。
动态部分的标记是这样的:
//begin form
<!-- ko foreach: durationValues -->
<div class="form-group">
<!-- ko if: ($index() === 0) -->
<label for="Values[0].Value">Values</label>
<!-- /ko -->
<div class="input-group">
<input class="form-control" type="text" data-bind="value: text, attr: { name: 'Values[' + $index() + '].Value' }" data-val="true" data-val-required="Value required." />
<span class="input-group-btn">
<!-- ko if: ($index() === 0) -->
<button class="btn btn-outline-secondary" type="button" data-bind="click: addDurationValue"><i class="fa fa-plus-circle"></i> Add</button>
<!-- /ko -->
<!-- ko if: ($index() > 0)-->
<button class="btn btn-outline-secondary" type="button" data-bind="click: $parent.removeDurationValue"><i class="fa fa-trash"></i> Remove</button>
<!-- /ko -->
</span>
</div>
<span class="field-validation-valid invalid-feedback" data-bind="attr: { 'data-valmsg-for': 'Values[' + $index() + '].Value' }" data-valmsg-replace="true"></span>
</div>
<!-- /ko -->
//endform
//jquery, jquery-validate, jquery-validate-unobtrusive, bootstrap and knockout script files loaded
<script>
function DurationValue(text) {
this.text = text;
}
function DurationValuesViewModel() {
var self = this;
self.durationValues = ko.observableArray([
new DurationValue("")
]);
self.addDurationValue = function () {
self.durationValues.push(new DurationValue(""));
//Remove current form validation information
$("form")
.removeData("validator")
.removeData("unobtrusiveValidation");
//Parse the form again
$.validator.unobtrusive.parse("form");
};
self.removeDurationValue = function (durationValue) { self.durationValues.remove(durationValue); };
}
ko.applyBindings(new DurationValuesViewModel());
</script>
页面不断向我大喊这些错误:
未捕获的引用错误:
无法处理绑定“foreach: function (){return durationValues }”
消息:无法处理绑定“if: function (){return ($index() === 0) }”
消息:无法处理绑定“点击:函数(){return addDurationValue}”
消息:未定义 addDurationValue 单击时(在 createBindingsStringEvaluator 进行评估(knockout-3.4.2.debug.js:2992),:3:58) 在 newValueAccessor (knockout-3.4.2.debug.js:4231) 在初始化 (knockout-3.4.2.debug.js:4241) 在初始化 (knockout-3.4.2.debug.js:4234) 在淘汰赛-3.4.2.debug.js:3368 在 Object.ignore (knockout-3.4.2.debug.js:1480) 在淘汰赛-3.4.2.debug.js:3367 在 Object.arrayForEach (knockout-3.4.2.debug.js:159) 在 applyBindingsToNodeInternal (knockout-3.4.2.debug.js:3353) 在 applyBindingsToNodeAndDescendantsInternal (knockout-3.4.2.debug.js:3233)
【问题讨论】:
标签: javascript jquery knockout.js