我有一个用户表,我需要根据更改的单选按钮按活动进行过滤。
我是用Knockout做的,但它不起作用,我没有收到错误,但表格空了,我做错了吗?
如果没有过滤,页面就会完美运行(当foreach在users
而非filteredUsers
时)
单选按钮:
<div class="btn">
<input id="active" checked class="filterOpt selectedRadio" name="filterOpt" type="radio" data-bind="checked: inactive, attr: { 'value': 'false' }" /> <label class="filterLbl selectedRadio" for="active">ACTIVE</label>
</div>
<div class="btn">
<input id="inActive" class="filterOpt" name="filterOpt" type="radio" data-bind="checked: inactive, attr: { 'value': 'true' }" /> <label class="filterLbl" for="inactive">INACTIVE</label>
</div>
<div class="btn">
<input id="all" class="filterOpt" name="filterOpt" type="radio" data-bind="checked: inactive, attr: { 'value': 'all' }" /> <label class="filterLbl" for="all">ALL</label>
</div>
和KO代码:
self.users= ko.observableArray([]);
self.inactive = ko.observable();
self.filteredClients = ko.observableArray([]);
self.filteredUsers= ko.computed(function () {
var val = self.inactive();
return self.users().filter(function (item) {
console.log(ko.toJSON(item));
return item.inactive === val;
});
});
然后我的桌子:
<!--ko foreach: filteredUsers-->
<table class="table">
<tr class="header">
<td class="name n" data-bind="text: name"></td>
<td class="rep" data-bind="text: email"></td>
<td class="status" data-bind="text: inactive"></td>
</tr>
</table>
答案 0 :(得分:1)
您的单选按钮会将所选值作为字符串返回。如果User对象具有inactive
作为布尔值,那么===
总是会返回false,因为您正在将布尔值与字符串进行比较。
这是一个Codepen作为例子。您可以看到User 2
的真值为布尔值,而不显示(User 1
显示)。
这是User
对象:
function User(name, inactive){
var self = this;
self.inactive = inactive;
self.name = name;
self.email = "aaa@a.com"
}
这是ViewModel:
function ViewModel() {
self.users= ko.observableArray([
new User('User 1', 'true'),
new User('User 2', true),
new User('User 3', 'false'),
]);
self.inactive = ko.observable();
self.filteredClients = ko.observableArray([
]);
self.filteredUsers= ko.computed(function () {
var val = self.inactive();
return self.users().filter(function (item) {
console.log(ko.toJSON(item));
return (item.inactive === val) || (val === 'all');
});
});
}
如您所见,我创建了三个User
:
new User('User 1', 'true'),
new User('User 2', true),
new User('User 3', 'false'),
第二个以true
为布尔值,其他有一个字符串。如果用文本更改布尔值,则会显示两个用户。
拜托,请给你回答。
: - )
答案 1 :(得分:1)
在@ JoseLuis的回答之后,我能够通过一些小的改动来实现它,我发布它以防将来有人会遇到类似的问题。
正如@JoseLuis所提到的问题是D:\projects\foo
和Boolean
的比较,为了解决我将String
解析为String
然后我得到了一个比较在两个布尔之间。
这就是整个功能:
Boolean