簡體   English   中英

單擊列表元素即可顯示和隱藏div

[英]Show and hide divs on click of a list element

我有這個清單:

<ul class="filters">
      <li id="all">All</li>
      <li id="cat1">Cat1</li>
      <li id="cat2">cat2</li>
      <li id="cat3">cat3</li>
</ul>

<div class="col s12 m4 l3 category-cat1">
     <div class="card-panel grey lighten-5 z-depth-1">
       <div class="row">
          <div class="col s4">
            <img src="/static/images/cat124.jpg" alt="" class="circle responsive-img">
          </div>
          <div class="col s8">
             <span class="black-text">
                This is a square image. Add the "circle" class to it to make it appear circular.
             </span>
          </div>
        </div>
        <a href="/">View Details</a>
      </div>
</div>
....
....

而此JS代碼在頁面末尾:

$('.filters li').click(function () {
        $('[class^=category-]').hide('fast','linear');
        var id = $(this).attr('id');
        if(id == 'all') {
             $('[class^=category-]').show('fast','linear');
        } else {
             $('.category-'+id).show('fast','linear');
        }
    });

我嘗試通過過濾器顯示和隱藏具有相同類別的div。 我以為這很容易,但是當我單擊<li>什么也沒有發生。 控制台上沒有錯誤,也沒有div上的更改。

問題是選擇器^= ,這是屬性以選擇器開頭 ,您的類名屬性值不是以category-開頭,這就是為什么它不起作用的原因。

相反,try屬性包含選擇器

$('[class*=category-]').hide('fast','linear');

但是正確的解決方案可能是向這些div元素(如category添加一個category

<div class="col s12 m4 l3 category-cat1 category">
</div>

然后用它

$('div.category').hide('fast','linear');

您使用了錯誤的屬性選擇器。

^的意思是開頭,而您的class屬性則不是。 使用*表示“包含子字符串”。

您遇到的第二個問題是ID比較僅使用2 ==,這是JavaScript的比較弱。 將此更改為3 ===,一切將開始工作。

看到這個JSFiddle: http : //jsfiddle.net/bey3wpt2/

另請參閱下文。

$('.filters li').click(function () {
    var id = $(this).attr('id');

    $('[class*=category-]').hide('fast', 'linear');

    if (id === 'all') {
        $('[class*=category-]').show('fast', 'linear');
    } else {
        $('.category-' + id).show('fast', 'linear');
    }
});

Ps我移到頂部的var id的唯一原因是為了滿足JSLint。

在這里,問題是給定選擇器格式[attribute ^ ='startingString']將返回屬性以給定字符串開頭的元素。

<div class="col s12 m4 l3 category-cat1"> // here, class start with "col" so no element will be select. So selector is need to change like below format.




  $("[class^='col']").hide('fast', 'linear');

//selector start with "col"

或對所有具有類屬性值包含單詞“ category-”的元素使用*

暫無
暫無

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

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