2
我正在使用錶行過濾腳本。隱藏除過濾對象中定義的ID以外的所有錶行
最初,所有的表格行都是可見的,但是在操作了一些下拉菜單/表格之後,過濾條件決定了哪些行將可見,哪些不可見。例如:
var jobs = [{
id: 0,
company: "Google",
location: "Zurich"
}, {
id: 1,
company: "Facebook",
location: "Ireland"
}];
// this function isn't run in this example for reasons of brevity. it's to show how the jobs array is generated
const filterRow = function (data, filters) {
let filtersEnabled = Object.keys(filters).filter(element => filters[element].length !== 0);
return data.filter(row => {
return filtersEnabled.every(k => {
return filters[k].indexOf(row[k]) !== -1
})
})
}
let $tableRows = $('table tbody tr');
const updateDisplay = function() {
// that's not ideal
$tableRows.addClass('hidden')
jobs.forEach((row) => {
$(`[data-id="${row.id}"]`).removeClass('hidden')
})
}
$('.js-filter').on('click',() => updateDisplay())
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<button class="js-filter">filter table now</button>
<table class="table table-bordered">
<tbody>
<tr data-company="google" data-id="0" data-loation="zurich">
<td>Google</td>
<td>Zurich</td>
<td>0</td>
</tr>
<tr data-company="facebook" data-id="1" data-loation="ireland">
<td>Facebook</td>
<td>Ireland</td>
<td>1</td>
</tr>
<tr data-company="microsoft" data-id="2" data-loation="california">
<td>microsoft</td>
<td>California</td>
<td>2</td>
</tr>
</tbody>
</table>
的作業陣列確定哪些行要可見。 (所以在這種情況下,只有ID爲0和1的行纔會被看到
鑑於jobs數組正在以編程方式改變,我想用jQuery(或其他)方法直接隱藏帶ID的行不存在陣列中(從而是能夠使用animate.css淡出排出來等
我目前做的是
- 隱藏所有行,
- 然後顯示在陣列中的人。那是相當一個解決方法,它使我的轉換/動畫複雜化。
感謝,工作,接受,但兩個問題:1 /我們可以使用。不()爲此並簡化它?我實際上正在運行另一個產生'jobs'數組的循環,所以想知道我是否可以直接在那裏做??(檢查更新的問題)2 /有什麼方法可以使用「===」而不是「== 「?我知道id是一個數字,而不是一個字符串.. –
@GeorgeKatsanos - 好吧,我使用'.not()'方法添加了一個示例。我不確定你傳遞給'filterRow'函數的數據是什麼,所以我不確定這個......對於2),我更新它以使用'==='。我最初使用'=='的原因是因爲數據屬性返回一個字符串,(即'typeof row.dataset.id'是'string')。我剛剛在屬性值前面加了一個'+'以將其強制轉換爲數字。 –