Kin*_*ien 46 javascript jquery knockout.js
怎样才能使knockout数据绑定对动态生成的元素起作用?例如,我在div中插入一个简单的html选择菜单,并希望使用knockout选项绑定填充选项.这就是我的代码:
$('#menu').html('<select name="list" data-bind="options: listItems"></select>');
Run Code Online (Sandbox Code Playgroud)
但这种方法不起作用.有任何想法吗?
PlT*_*lor 31
如果在绑定viewmodel后动态添加此元素,则它将不在viewmodel中,并且不会更新.你可以做两件事之一.
ko.applyBindings();
再次调用重新绑定它Ste*_*cus 12
淘汰赛3.3
ko.bindingHandlers.htmlWithBinding = {
'init': function() {
return { 'controlsDescendantBindings': true };
},
'update': function (element, valueAccessor, allBindings, viewModel, bindingContext) {
element.innerHTML = valueAccessor();
ko.applyBindingsToDescendants(bindingContext, element);
}
};
Run Code Online (Sandbox Code Playgroud)
上面的代码片段允许您使用"htmlWithBinding"属性动态注入html元素.然后还评估添加的子元素......即它们的数据绑定属性.
小智 10
重写html绑定代码或创建一个新的.因为html绑定阻止了动态html中的"注入绑定":
ko.bindingHandlers['html'] = {
//'init': function() {
// return { 'controlsDescendantBindings': true }; // this line prevents parse "injected binding"
//},
'update': function (element, valueAccessor) {
// setHtml will unwrap the value if needed
ko.utils.setHtml(element, valueAccessor());
}
};
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
58562 次 |
最近记录: |