我遇到了一个有趣的小问题,涉及动态设置一组div的类。
使用Knockout.js,我通过“attr”绑定来分配所使用的类。
在我测试过的所有浏览器中,这都很好用,除了IE-7(不担心IE-6等)
我有一个jsfiddle示例突出显示了此问题。
在示例中,静态行(顶部)应该与底部(ko生成的)匹配,在IE-7中,我只看到最广泛的CSS选择器颜色(银色)。
我遇到了一个有趣的小问题,涉及动态设置一组div的类。
使用Knockout.js,我通过“attr”绑定来分配所使用的类。
在我测试过的所有浏览器中,这都很好用,除了IE-7(不担心IE-6等)
我有一个jsfiddle示例突出显示了此问题。
在示例中,静态行(顶部)应该与底部(ko生成的)匹配,在IE-7中,我只看到最广泛的CSS选择器颜色(银色)。
IE7需要使用className
而不是class
。
例如,在IE7和其他浏览器中,以下代码都可以正常工作:http://jsfiddle.net/thirtydot/VVuGh/14/
<div data-bind='attr: { "class": classes, "className": classes }'></div>
然而,最好不要在你的HTML中支持IE7的这个怪异行为。将其放在knockout.js中会更好,尽管我对该库一无所知,无法做出这样的建议。
如果在生成模板时无法确定类名(即它是您的模型的一部分),则可以创建一个自定义绑定。
您的init
/ update
方法的内容只需根据valueAccessor
返回的内容为element
设置类名。 例如,您可以使用以下简单示例(使用jQuery):
ko.bindingHandlers.yourBindingName = {
init: function(element, valueAccessor, allBindingsAccessor, viewModel) {
// This will be called when the binding is first applied to an element
// Set up any initial state, event handlers, etc. here
$(element).addClass(valueAccessor());
},
update: function(element, valueAccessor, allBindingsAccessor, viewModel) {
// This will be called once when the binding is first applied to an element,
// and again whenever the associated observable changes value.
// Update the DOM element based on the supplied values here.
}
};
你可以基于 knockout css binding 构建一个更复杂的绑定。