2017-08-15 78 views
0

我正在從lynda.com(關於jquery)做一個編程挑戰。 我被要求這樣做,使複選框允許用戶隱藏關於銷售運動/健康產品的頁面的產品,當它們未被選中時,並且當他們再次被檢查時將其顯示在列表中。當我取消選中該複選框時,我可以隱藏這些catigories,但當我再次查看時,它們不會再顯示。 這裏是jQuery代碼第一個(我不偉大縮進道歉):隱藏在jquery中後顯示內容的麻煩

$("document").ready(function() { 
 
     var combo = $("input[name=vitamin]").add("input[name=proteinbar]").add("input[name=mineralwater]"); 
 
     combo.on("change", function() { 
 
     var name = $(this).attr("name"); 
 
     if (!$(this).checked) { 
 
      filterList(name, $(this)); 
 
     } 
 
     if ($(this).checked) { 
 
      unfilterList(name, $(this)); 
 
     } 
 
     }); 
 
    }); 
 

 
    function filterList(name, selector) { 
 
     $(".product-item").each(function(index) { 
 
     if (($(this).children("h2").data("type") == name) && !selector.checked) { 
 
      $(this).hide(); 
 
     } 
 
     }); 
 
    } 
 

 
    function unfilterList(name, selector) { 
 
     $(".product-item").each(function(index) { 
 
     if (($(this).children("h2").data("type") == name)) { 
 
      $(this).show(); 
 
     } 
 
     }); 
 
     return false; 
 
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<form > 
 
      show:</br> 
 
      <input type="checkbox" checked value="mineralWater" name="mineralwater" />Mineral Water <br> 
 
      <input type="checkbox" value="proteinbar" name="proteinbar" checked /> protein bars 
 
      <input type="checkbox" checked value="Vitamins" name="vitamin" /> vitamins <br> 
 
     </form> 
 
     <ul class="product-list"> 
 
     <li class="product-item" data-prod_id="V-A1037"> 
 
      <img class="product-image" src="images/products/vitamin-a.jpg" alt="Vitamin A - Product Photo"> 
 
      <h2 class="product-name" data-type="vitamin">Vitamin A</h2> 
 
     </li> 
 
     <li class="product-item" data-prod_id="V-BC2178"> 
 
      <img class="product-image" src="images/products/vitamin-bcomplex.jpg" alt="B Complex - Product Photo"> 
 
      <h2 class="product-name" data-type="vitamin">Vitamin-B Complex</h2> 
 
     </li> 
 
     <li class="product-item" data-prod_id="MW-8812"> 
 
      <img class="product-image" src="images/products/mineralwater-blueberry.jpg" alt="Blueberry Mineral Water - Product Photo"> 
 
      <h2 class="product-name" data-type="mineralwater">Blueberry Mineral Water</h2> 
 
     </li>

+0

如果這對你來說是一個挑戰,我認爲你應該自己動手。 – guradio

+0

我大部分時間都在做。我有一半工作。 – hamero

回答

1

你應該改變$(this).checkedthis.checked$(this).prop('checked'),我想。

+1

或'$(this).is(「:checked」)' – Barmar

+0

工作正常!謝謝。我不明白,但我喜歡它!謝謝 – hamero

+0

@hamero'$(this)'是一個沒有'checked'屬性的jQuery對象,所以'$(this).checked'永遠是undefined(false)。但是'this.checked'會隨着你的點擊而改變,因爲'this'是指複選框。所以'$(this).prop('checked')'也會起作用。 – LIXer