【问题标题】:knockout(js) to the (html)head淘汰(js)到(html)头
【发布时间】:2015-07-25 06:41:26
【问题描述】:
敲除在 HTML 文档的头部不起作用吗?
我正在尝试绑定样式表的href -
<html>
<head>
<link type="text/css" data-bind="attr: { href: myStyleSheet }" rel="stylesheet">
</head>
<body>
<script>
var ViewModel = function() {
this.myStyleSheet = ko.observable('/css/stylea.css');
};
ko.applyBindings(new ViewModel());
</script>
</body>
</html>
动态 dom 就是这个样子 -
<link rel="stylesheet" type="text/css" data-bind="attr: { href: myStyleSheet }">
什么都没有发生。
【问题讨论】:
标签:
javascript
knockout.js
【解决方案1】:
您可以将目标指定为ko.applyBindings() 的第二个参数。我不确定你是否可以指定head,试试看。如果您不指定任何内容,则会进入以下code:
ko.applyBindings = function (viewModelOrBindingContext, rootNode) {
// If jQuery is loaded after Knockout, we won't initially have access to it. So save it here.
if (!jQueryInstance && window['jQuery']) {
jQueryInstance = window['jQuery'];
}
if (rootNode && (rootNode.nodeType !== 1) && (rootNode.nodeType !== 8))
throw new Error("ko.applyBindings: first parameter should be your view model; second parameter should be a DOM node");
rootNode = rootNode || window.document.body; // Make "rootNode" parameter optional
applyBindingsToNodeAndDescendantsInternal(getBindingContext(viewModelOrBindingContext), rootNode, true);
};
在这里您可以看到它选择window.document.body 作为默认值,因此不会获得head。