簡體   English   中英

jquery - 在 data-id 數組中按元素顯示/隱藏元素行

[英]jquery - show / hide elements rows by elemenst in data-id array

我有這樣的行表:

<tr class="listRow" data-id="[11,0]">...</tr>
<tr class="listRow" data-id="[1,2,3]">...</tr>

我如何使用 JQuery 過濾具有數組中元素的特定行? 例如,通過按鈕單擊顯示數組中具有 1 的所有行並隱藏 rest。

編輯 - 到目前為止我的示例代碼:

我不知道如何過濾 data-id 數組中的元素。

$(document).on('click','#filterList',function()
    {
        var element = $(this).data("id");

// how to filter elements in rows

    }
);
  • 當您按下按鈕時,循環遍歷所有具有data-id的元素
  • 將 data-id 解析為 json,這將為您提供一個數組
  • 如果數組包含您要查找的 id,請將 class 設置為hideshow (其中相應分配了顯示 css)

這是沒有 jquery 並使用樣式和不透明度的情況。 通常使用 class 完成,但這是出於演示目的,更改為使用類應該是直截了當的。

 function findElsById(id){ var matches = [] document.querySelectorAll('[data-id]').forEach(function(el){ try{ var arr = JSON.parse(el.dataset.id) if (arr.includes(id)) matches.push(el) } catch (e){ // prolly not valid json } }) return matches } function show(id){ var els = findElsById(id); console.log('show', id, '\nshowing: ', els) if (els) { els.forEach(function(el){ el.style = 'opacity:1' }) } } function hide(id){ var els = findElsById(id); console.log('hide', id, '\nhiding: ', els) if (els) { els.forEach(function(el){ el.style = 'opacity:0.1' }) } }
 <table> <tr class="listRow" data-id="[1,0]"><td>1, 0</td></tr> <tr class="listRow" data-id="[1,2]"><td>1, 2</td></tr> </table> <button onclick="hide(0)">-0</button> <button onclick="hide(1)">-1</button> <button onclick="hide(2)">-2</button> <button onclick="show(0)">+0</button> <button onclick="show(1)">+1</button> <button onclick="show(2)">+2</button>

如果我理解正確:

$('#check').click(function() {

$('.listRow').each(function() {
if($.inArray(1, $(this).data().id)>-1) {
$(this).show();
}
else {
$(this).hide()
}


});
});

 $('#check').click(function() { $('.listRow').each(function() { if($.inArray(1, $(this).data().id)>-1) { $(this).show(); } else { $(this).hide() } }); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <table class="tg"> <thead> <tr class="listRow" data-id="[1,0]"> <th class="tg-0pky">Here is 1</th> <th class="tg-0pky">xxxx</th> <th class="tg-0pky"></th> <th class="tg-0pky"></th> </tr> </thead> <tbody> <tr class="listRow" data-id="[11,0]"> <td class="tg-0pky">Not 1</td> <td class="tg-0pky"></td> <td class="tg-0pky"></td> <td class="tg-0pky"></td> </tr> <tr class="listRow" data-id="[15,0]" > <td class="tg-0pky">Not 1</td> <td class="tg-0pky"></td> <td class="tg-0pky"></td> <td class="tg-0pky"></td> </tr> <tr class="listRow" data-id="[1,0,3]"> <td class="tg-0pky" >Here is 1</td> <td class="tg-0pky"></td> <td class="tg-0pky"></td> <td class="tg-0pky"></td> </tr> </tbody> </table> <button id="check"> Click </button>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM