首页 > 解决方案 > 通过 jquery 访问 div 元素数组到 .show() 或 .hide() 每个单独用于轮播

问题描述

我正在 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>

标签: javascripthtmljqueryarrayselement

解决方案


兄弟,你可以试试这个。我看到你给出profiles了类名,但在 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>


推荐阅读