jquery 如何避免在访问除第一个子元素以外的每个元素时循环

a6b3iqyw  于 2023-05-17  发布在  jQuery
关注(0)|答案(2)|浏览(102)
<div class="container">
   <div class="row m-0 be_product_grid_image">
      <divclass="col_classes">
      <img src="img1.png" />
   </div>
   <div class="row m-0 be_product_grid_image">
      <divclass="col_classes">
      <img src="img2.png" />
   </div>
   <div class="row m-0 be_product_grid_image">
      <divclass="col_classes">
      <img src="img3.png" />
   </div>
   <div class="row m-0 be_product_grid_image">
      <divclass="col_classes">
      <img src="img4.png" />
   </div>
   <div class="row m-0 be_product_grid_image">
      <divclass="col_classes">
      <img src="img5.png" />
   </div>
</div>

单击“显示全部”* 按钮 * 时,我想显示除第一个图像外的所有图像 ,同样,单击“显示较少 按钮 * 时,隐藏除第一个图像外的所有图像 *

z6psavjg

z6psavjg1#

var images = $('.be_product_grid_image:not(:first)');

$(document).on('click', 'your_show_all_button', function() {
     images.show()
})

$(document).on('click', 'your_show_less_button', function() {
     images.hide()
})

尝试应用此方法,将 your_show_all_buttonyour_show_less_button 替换为您的button的类或ID

hmae6n7t

hmae6n7t2#

为显示和隐藏添加两个按钮:

<button id="showAllBtn" onclick="showAllImages()">Show All</button>
<button id="showLessBtn" onclick="showLessImages()">Show Less</button>

为以下功能添加js脚本:

function showAllImages() {
   var images = document.querySelectorAll('.be_product_grid_image');

   for (var i = 0; i < images.length; i++) {
      images[i].style.display = 'block';
   }
   document.getElementById('showAllBtn').style.display = 'none';
   document.getElementById('showLessBtn').style.display = 'inline-block';
}

function showLessImages() {
   var images = document.querySelectorAll('.be_product_grid_image');

   for (var i = 1; i < images.length; i++) {
      images[i].style.display = 'none';
   }
   
   document.getElementById('showAllBtn').style.display = 'inline-block';
   document.getElementById('showLessBtn').style.display = 'none';
}

相关问题