通过 jquery 访问 div 元素的数组到 .show() 或 .hide() 每个 dividually 轮播

Access array of div elements via jquery to .show() or .hide() each one individually for carousel

我正在 javascript/jquery 中创建个人资料页面,我正在使用 div 的轮播来完成上述任务。我的问题是,如何以编程方式访问每个 style.display 或 $("#username").hide() 或 .show() ?

function changeProfile(num) {
  var profiles = $('#profiles');
  if (num < 1) {
    index = 3;
  }
  if (num > 3) {
    index = 1;
  }
  for (i = 0; i < 3; i++) {
    profiles[i].style.display = "none"; // error here
    // for example: $('#profiles')[0];  etc
  }
  profiles[index - 1].style.display = "block";
  console.log("Profile number: " + index);
}
<div class="profiles">
  1 / 3
  <img src="images/blank1.jpg" style="width:90%">
</div>
<div class="profiles">
  2 / 3
  <img src="images/blank2.jpg" style="width:90%">
</div>
<div class="profiles">
  3 / 3
  <img src="images/blank.jpg" style="width:90%">
</div>

你可以使用每个函数然后获取元素的索引来做一些事情

https://api.jquery.com/each/

function changeProfile(num) {
  $('.profiles').each(function(index, value) {
    if (num == index) {
      console.log('Get selected num: ' + num);
      $(this).fadeOut();
    } else {
      console.log(`div${index}: ${this.id}`);
    }
  });
}

changeProfile(0);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="profiles">
    1 / 3
    <img src="images/blank1.jpg" style="width:90%">
</div>
<div class="profiles">
    2 / 3
    <img src="images/blank2.jpg" style="width:90%">
</div>
<div class="profiles">
    3 / 3
    <img src="images/blank.jpg" style="width:90%">
</div>

兄弟,你可以试试这个。我看到您将 profiles 作为 class 名称,但在 js 中您搜索的是 id。这就是 profiles[] 返回 null 的原因。

function changeProfile(num) {
    var profiles = $('.profiles');
    
    if (num < 1) {
        index = 3;
    }
    
    if (num > 3) {
        index = 1;
    }
    
    for (i = 0; i < 3; i++) {
        profiles[i].style.display = "none"; // error here
    }
    
    profiles[num - 1].style.display = "block";
}

changeProfile(2)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="profiles">
   1 / 3
  <img src="https://neersyde.com/wp-content/uploads/2019/04/https___cdn.cnn_.com_cnnnext_dam_assets_190403144228-avengers-endgame-thumb-imax-poster-900x506.jpg" style="width:200px">
</div>
<div class="profiles">
  2 / 3
  <img src="https://images.hdqwalls.com/wallpapers/logan-and-x23-4k-2y.jpg" style="width:200px">
</div>
<div class="profiles">
  3 / 3
  <img src="https://akm-img-a-in.tosshub.com/sites/btmt/images/stories/avengers_endgame_660_050719024159.jpg" style="width:200px">
</div>