【发布时间】:2013-09-20 11:29:09
【问题描述】:
我正在尝试在一些现有应用程序中连接 knockout.js。 绑定以一些神秘的方式起作用。如果我使用 p 标签,它会完全搞乱绑定。 如果我使用标签标签,它也会弄乱绑定。
例如:
<p data-bind="foreach: currentFields">
<p data-bind="foreach: props">
<span data-bind="text: type"></span>
</p>
</p>
这行不通。如果我更改为跨度,它会起作用。 但是后来我遇到了标签标签的问题。如果我删除标签,则绑定有效。
如果我使用除了普通跨度之外的任何东西,自动绑定似乎完全搞砸了。 是否有合适的 javascript 绑定库? Angular.js 在这方面更好吗? 因为仅仅为了取悦knockout.js而重写所有现有的HTML,包括CSS真的一点都不好玩:)
示例代码:
<p>
<span data-bind="foreach: currentFields">
<span data-bind="text: value"></span>
<span data-bind="text: type"></span>
<span data-bind="text: selected"></span>
<span data-bind="text: props"></span>
<span data-bind="foreach: props, visible: selected">
<li>
<label>Labela:</label>
<span>
<span data-bind="text: type"></span>
<input type="text" data-bind="value: type, valueUpdate: 'afterkeydown'" required="required" maxlength="140" ></input>
</span>
</li>
</span>
</span>
</p>
var Property = function(type) {
this.type = ko.observable(type);
}
var Field = function(value) {
this.props = ko.observableArray([new Property("a"), new Property("b")]);
this.type = ko.observable('text');
this.value = ko.observable(value);
this.selected = ko.observable(false);
};
var myViewModel = function () {
var self = this;
this.currentFields = ko.observableArray([new Field("a"), new Field("b")]);
this.currentField = ko.observable();
this.addField = function() {
self.currentFields.push(new Field("xyz"));
};
this.selectField = function(field) {
ko.utils.arrayForEach(self.currentFields(), function(item) {
item.selected(false);
});
field.selected(true);
self.currentField(field);
};
};
$(document).ready(function() {
ko.applyBindings(new myViewModel());
});
【问题讨论】:
-
断点是什么意思?绑定在所有 HTML 标记中都可以正常工作。但是,在彼此之间嵌套
标签在语义上是无效的。打破是什么意思?
-
看来问题是如果我把 p 放在 span 周围。我已经“修复”了 html。
-
问题不在于
p和span。您不能在p中包含li,因为根据 HTML 规范,它不是有效的 HTML(p只能包含 Phrasing content)。请参阅此相关问题:stackoverflow.com/questions/18869466/…。
标签: javascript angularjs knockout.js