jQuery 多次悬停显示 DIV 重构

jQuery Multiple Hover to Show DIV Refactor

我正在尝试使用最优雅的解决方案来缩短这段代码。如果有人可以提供帮助,我会喜欢一些意见。谢谢!我认为有更好的方法来解决它。 类 切换会更好吗?任何建议表示赞赏。非常感谢你。

$(document).ready(function() {
  $(".olay-1").hover(function() {
    $(".hpanel-1").fadeIn(500);
  }, function() {
    $(".hpanel-1").fadeOut(500);
  });
  $(".olay-2").hover(function() {
    $(".hpanel-2").fadeIn(500);
  }, function() {
    $(".hpanel-2").fadeOut(500);
  });
  $(".olay-3").hover(function() {
    $(".hpanel-3").fadeIn(500);
  }, function() {
    $(".hpanel-3").fadeOut(500);
  });
  $(".olay-4").hover(function() {
    $(".hpanel-4").fadeIn(500);
  }, function() {
    $(".hpanel-4").fadeOut(500);
  });
});


  <div class="hpanel-1">
      <h2>Hidden Text</h2>
  </div>
  <div class="hpanel-2">
      <h2>Hidden Text</h2>
  </div>
        <div class="hanel-3">
      <h2>Hidden Text</h2>
  </div>
        <div class="hpanel-4">
      <h2>Hidden Text</h2>
  </div>


    <div class="container">

      <div class="olay-1">
        Here is the info
      </div>
      <div class="olay-2">
        Here is the info
      </div>
      <div class="olay-3">
        Here is the info
      </div>
      <div class="olay-4">
        Here is the info
      </div>

    </div>

如果你总是保持这个顺序(olay-i 淡出 hpanel-i),你可以使用这个:

<!doctype html><html><head><title>Test</title>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script>
$(document).ready(function() {
  $(".olay").hover(function() {
    $(".hpanel").eq($(this).index()).fadeIn(500);
  }, function() {
    $(".hpanel").eq($(this).index()).fadeOut(500);
  });
});
</script>
</head>
<body>

  <div class="hpanel">
      <h2>Hidden Text</h2>
  </div>
  <div class="hpanel">
      <h2>Hidden Text</h2>
  </div>
  <div class="hpanel">
      <h2>Hidden Text</h2>
  </div>
  <div class="hpanel">
      <h2>Hidden Text</h2>
  </div>

  <div class="container">

  <div class="olay">
    Here is the info
  </div>
  <div class="olay">
    Here is the info
  </div>
  <div class="olay">
    Here is the info
  </div>
  <div class="olay">
    Here is the info
  </div>
</div>
</body></html>