简体   繁体   English

根据data- *属性控制div的显示

[英]Control display of a div based on data-* attribute

I am showing articles in a list of divs. 我在div列表中显示文章。 Each div has a data attribute that contains the status of the article. 每个div都有一个数据属性,其中包含文章的状态。

<div id="article_1" data-status="read"> ... </div>
<div id="article_2" data-status="unread"> ... </div>

There is a button that toggles views to show "All Articles" or only "Unread" articles. 有一个按钮可切换视图以显示“所有文章”或仅显示“未读”文章。

My toggle function looks like this, which is working fine: 我的切换功能如下所示,可以正常工作:

function toggle(status) {
    if (status == 'all') {
         $('*').filter(function() {
            if ($(this).data('status') == "read") {
                $(this)[0].style.display = 'block';
            }
         });  
    }
    else {
         $('*').filter(function() {
            if ($(this).data('status') == "read") {
                $(this)[0].style.display = 'none';
            }
         });
    }
}

Question : Is there a better (faster, efficient) way to select divs with data-status attribute and based on the status toggle the view? 问题 :是否有更好(更快,更有效)的方法来选择具有data-status属性的div,并根据状态切换视图?

Ref: 参考:

[1] Jquery select all elements that have $jquery.data() [1] jQuery选择所有具有$ jquery.data()的元素

[2] Show/hide multiple divs based on a value in their attribute [2] 根据属性中的值显示/隐藏多个div

[3] filtering divs in jQuery and hiding them based on a custom data attribute tag [3] 在jQuery中过滤div并根据自定义数据属性标签将其隐藏

You can just select on the data-status attribute itself: 您可以只选择data-status属性本身:

 function toggle(status) { if (status == 'all') { $('[data-status=read]').css('display', 'block'); } else { $('[data-status=read]').css('display', 'none'); } } toggle('unread'); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div id="article_1" data-status="read"> read </div> <div id="article_2" data-status="unread"> unread </div> 

I think you can go very simple here: 我认为您可以在这里进行以下操作:

function toggle(status) {
  if (status == 'all') {
    $('*[data-status="read"]').show();
  } else {
    $('*[data-status="read"]').hide();
  }
}

Hope that helps 希望能有所帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM