javascript Knockout.js“全选”复选框
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5969162/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Knockout.js "select all" checkboxes
提问by dmackerman
I've just started playing around with Knockout.js, and it seems really cool. What I have is a grid. This grid has a column with a checkbox at the top to "select all" of the elements, as well as deselect. Standard grid behavior.
我刚刚开始玩 Knockout.js,它看起来真的很酷。我拥有的是一个网格。该网格有一个顶部带有复选框的列,用于“选择所有”元素以及取消选择。标准网格行为。
Here's my code so far:
到目前为止,这是我的代码:
Javascript:
Javascript:
// Define a "banner" class
function banner(inventory, name, artType, artSize) {
return {
isSelected : ko.observable(false),
inventory : ko.observable(inventory),
name : ko.observable(name),
artType : ko.observable(artType),
artSize : ko.observable(artSize)
};
}
var viewModel = {
banners : ko.observableArray([new banner("network", "Banner #1"), new banner("oo", "Banner #2")]),
addBanner : function() {
this.banners.push(new banner("network", "Banner"));
},
selectAll : function() {
this.banners.isSelected(true)
}
};
ko.applyBindings(viewModel);
I'm binding the "selectAll" event to the checkbox like this:
我将“selectAll”事件绑定到这样的复选框:
<th><input data-bind="click: selectAll" type="checkbox" /></th>
And for each individual banner I have in my list, their checkbox looks like this:
对于我列表中的每个横幅,它们的复选框如下所示:
<td><input data-bind="checked: isSelected" type="checkbox" /></td>
For some reason my selectAll function isn't working correctly. I'm fairly new to this OO javascript programming paradigm, so I may be doing something blatantly wrong here.
出于某种原因,我的 selectAll 功能无法正常工作。我对这种 OO javascript 编程范式还很陌生,所以我可能在这里做错了一些事情。
Thanks!
谢谢!
回答by RP Niemeyer
banners is an array in this case, so you would need to access each item in the array and update the individual isSelected properties.
在这种情况下,横幅是一个数组,因此您需要访问数组中的每个项目并更新各个 isSelected 属性。
Something like:
就像是:
ko.utils.arrayForEach(this.banners(), function(banner) {
banner.isSelected(true);
});
回答by zshift
There's a more functional response at the link below. It deselects the "select all" box when on of the other checkboxes are deselected:
在下面的链接中有一个更实用的响应。当取消选择其他复选框时,它会取消选择“全选”框: