Как выбрать значение отмеченного флажка? - PullRequest
2 голосов
/ 30 сентября 2019

У меня есть четыре флажка. Основываясь на флажке, который отмечен (или не отмечен), мне нужно addClass (или removeClass) класса css для любого определенного div с классом filter-result И содержащего дочерний div с class, который соответствует значениюиз флажка отмечен. (Это для того, чтобы показать / скрыть результаты поиска, поэтому, установив / сняв флажки, можно отобразить / скрыть различные результаты поиска, имеющие соответствующие классы.)

Я могу написать четыре функции jquery, используя id s, которые практически идентичныза исключением id s, или я могу написать одну функцию jquery, используя переменные. Я предпочел бы написать только один, по понятным причинам. Я новичок в jQuery, JavaScript, PHP и т. Д., Поэтому я ожидаю, что моя ошибка здесь очень элементарна.

Это HTML / PHP:

<!-- HTML for the checkboxes -->
<label>
   <input type="checkbox" class="filterBox" value="devotion" id="toggleDevotion" checked/> Devotions
</label>
<label>
   <input type="checkbox" class="filterBox" value="blog" id="toggleBlog" checked/> Blog Posts
</label>
<label>
   <input type="checkbox" class="filterBox" value="product" id="toggleProduct" checked/> Products
</label>
<label>
   <input type="checkbox" class="filterBox" value="program" id="toggleProgram" checked/> Programs
</label>

<!-- HTML/PHP for the wordpress search results -->
<div class="rowSectionInner results-container">
   <?php if (have_posts() && strlen(trim(get_search_query())) != 0 ) { ?>
         <?php while (have_posts()) { the_post(); ?>
            <?php // Render a separation line. ?>
            <?php if ($hasLoopedOnce) { ?>
            <?php } $hasLoopedOnce = true; ?>
            <?php // Render the search result. ?>
            <div class="row justify-content-md-center filter-result">
               <div class="col-md-7">
                  <article>
                     . . . . . . . . . . . . . . .
                     <div class="siteSearch_date previewDate">
                        <?php echo get_the_date(); ?> <?php echo rename_post_types(get_post_type()); ?>
                     </div>
                     . . . . . . . . . . . . . . .
                  </article>
               </div>
            </div>
         <?php } ?>
   <?php } ?>
</div>

Это jQueryЯ написал, что работает, но супер неуклюже:

$('#toggleDevotion').click(function() {
   if( $(this).is(':checked')) {
      $('.siteSearch_date:contains("Devotion")').closest('.filter-result').removeClass('remove');
   } else {
      $('.siteSearch_date:contains("Devotion")').closest('.filter-result').addClass('remove');
   }
   if ($(".results-container").children().length == $(".results-container").children(".remove").length) {
      $(".no-results").css("display", "block");
      $("#wrapper").css({"display": "flex", "flex-direction": "column"});
      $("#container").css("flex-grow", "1");
   } else {
      $(".no-results").css("display", "none");
   }
}); 
$('#toggleBlog').click(function() {
   if( $(this).is(':checked')) {
      $('.siteSearch_date:contains("Blog")').closest('.filter-result').removeClass('remove');
   } else {
      $('.siteSearch_date:contains("Blog")').closest('.filter-result').addClass('remove');
   }
   if ($(".results-container").children().length == $(".results-container").children(".remove").length) {
      $(".no-results").css("display", "block");
   } else {
      $(".no-results").css("display", "none");
   }
}); 
$('#toggleProduct').click(function() {
   if( $(this).is(':checked')) {
      $('.siteSearch_date:contains("Product")').closest('.filter-result').removeClass('remove');
   } else {
      $('.siteSearch_date:contains("Product")').closest('.filter-result').addClass('remove');
   }
   if ($(".results-container").children().length == $(".results-container").children(".remove").length) {
      $(".no-results").css("display", "block");
   } else {
      $(".no-results").css("display", "none");
   }
}); 
$('#toggleProgram').click(function() {
   if( $(this).is(':checked')) {
      $('.siteSearch_date:contains("Program")').closest('.filter-result').removeClass('remove');
   } else {
      $('.siteSearch_date:contains("Program")').closest('.filter-result').addClass('remove');
   }
   if ($(".results-container").children().length == $(".results-container").children(".remove").length) {
      $(".no-results").css("display", "block");
   } else {
      $(".no-results").css("display", "none");
   }
});

Это jQuery, который я написал, чтобы попытаться объединить основной переключатель show / hide в одну функцию:

$(".filterBox").click(function() {  
   var $lemon = $(this).val();

   if( $(this).is(':checked')) {
      $(".siteSearch_date:contains($lemon)").closest('.filter-result').removeClass('remove');
   } else {
      $(".siteSearch_date:contains($lemon)").closest('.filter-result').addClass('remove');
   }
});

Я ожидаю, что он применяет или удаляет remove class из div с классом .filter-result - но я не получаю никакого ответа ни от чего, включая консоль. Чего мне не хватает?

1 Ответ

2 голосов
/ 30 сентября 2019

Правильный синтаксис для селектора:

$(".siteSearch_date:contains('"+$lemon+"')")

Редактировать ---

Следующий фрагмент должен имитировать ваш код, добавляя в качестве примера bakground, это то, чего вы хотели достичь?

$(".filterBox").click(function() {  
   var $lemon = $(this).val();

   if( $(this).is(':checked')) {
      $(".siteSearch_date:contains('"+$lemon+"')").closest('.filter-result').removeClass('remove');
   } else {  $(".siteSearch_date:contains('"+$lemon+"')").closest('.filter-result').addClass('remove');
   }
});
.remove{
  background-color: red;
  
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<label>
   <input type="checkbox" class="filterBox" value="devotion" id="toggleDevotion" checked/> Devotions
</label>
<label>
   <input type="checkbox" class="filterBox" value="blog" id="toggleBlog" checked/> Blog Posts
</label>
<label>
   <input type="checkbox" class="filterBox" value="product" id="toggleProduct" checked/> Products
</label>
<label>
   <input type="checkbox" class="filterBox" value="program" id="toggleProgram" checked/> Programs
</label>
<div class="row justify-content-md-center filter-result">
               <div class="col-md-7">
                  <article>
                     . . . . . . . . . . . . . . .
                     <div class="siteSearch_date previewDate">
                       product
                     </div>
                     . . . . . . . . . . . . . . .
                  </article>
               </div>
            </div>
            <div class="row justify-content-md-center filter-result">
               <div class="col-md-7">
                  <article>
                     . . . . . . . . . . . . . . .
                     <div class="siteSearch_date previewDate">
                       blog
                     </div>
                     . . . . . . . . . . . . . . .
                  </article>
               </div>
            </div>
            <div class="row justify-content-md-center filter-result">
               <div class="col-md-7">
                  <article>
                     . . . . . . . . . . . . . . .
                     <div class="siteSearch_date previewDate">
                       product
                     </div>
                     . . . . . . . . . . . . . . .
                  </article>
               </div>
            </div>
            <div class="row justify-content-md-center filter-result">
               <div class="col-md-7">
                  <article>
                     . . . . . . . . . . . . . . .
                     <div class="siteSearch_date previewDate">
                       program
                     </div>
                     . . . . . . . . . . . . . . .
                  </article>
               </div>
            </div>
            <div class="row justify-content-md-center filter-result">
               <div class="col-md-7">
                  <article>
                     . . . . . . . . . . . . . . .
                     <div class="siteSearch_date previewDate">
                       devotion
                     </div>
                     . . . . . . . . . . . . . . .
                  </article>
               </div>
            </div>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...