简体   繁体   中英

Control display of a div based on data-* attribute

I am showing articles in a list of divs. Each div has a data attribute that contains the status of the article.

<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?

Ref:

[1] Jquery select all elements that have $jquery.data()

[2] Show/hide multiple divs based on a value in their attribute

[3] filtering divs in jQuery and hiding them based on a custom data attribute tag

You can just select on the data-status attribute itself:

 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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