【问题标题】:Control display of a div based on data-* attribute根据 data-* 属性控制 div 的显示
【发布时间】:2015-12-07 20:20:07
【问题描述】:

我在 div 列表中显示文章。每个 div 都有一个包含文章状态的数据属性。

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

有一个按钮可以切换视图以显示“所有文章”或仅显示“未读”文章。

我的切换功能看起来像这样,工作正常:

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';
            }
         });
    }
}

问题:有没有更好(更快、更高效)的方法来选择具有data-status 属性并根据状态切换视图的 div?

参考:

[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

【问题讨论】:

    标签: javascript jquery html css


    【解决方案1】:

    您可以只选择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>

    【讨论】:

    • 完美!!干净利落。谢谢。
    【解决方案2】:

    我认为你可以在这里很简单:

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

    希望有帮助

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-14
      • 2011-09-02
      • 1970-01-01
      • 1970-01-01
      • 2013-11-22
      • 2018-11-28
      相关资源
      最近更新 更多