首页 > 解决方案 > 我怎样才能优化这个jquery?

问题描述

如果悬停另一个元素,我编写了一些 JS 代码来更改一个元素的 CSS 样式。我有 6 对元素。很明显,有更好的编码方式。请帮我。网站使用 Worpdress。

(function($) {
  $(document).ready(function() {
    $('.img-zink').hover(function() {
      $('#btn-zink').attr('style', 'background-color: #4aab61; color: white !important');
    }, function() {
      $('#btn-zink').attr('style', '');
    });

    $('.img-rist').hover(function() {
      $('#btn-rist').attr('style', 'background-color: #4aab61; color: white !important');
    }, function() {
      $('#btn-rist').attr('style', '');
    });

    $('.img-start').hover(function() {
      $('#btn-start').attr('style', 'background-color: #4aab61; color: white !important');
    }, function() {
      $('#btn-start').attr('style', '');
    });

    $('.img-humat').hover(function() {
      $('#btn-humat').attr('style', 'background-color: #4aab61; color: white !important');
    }, function() {
      $('#btn-humat').attr('style', '');
    });

    $('.img-bor').hover(function() {
      $('#btn-bor').attr('style', 'background-color: #4aab61; color: white !important');
    }, function() {
      $('#btn-bor').attr('style', '');
    });

  });
}(jQuery));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

标签: jquery

解决方案


您可以添加以下CSS

.active {
   background-color: #4aab61;
   color: white !important;
 }

然后像这样为一个hover()函数中的所有元素切换类:

 $('.img-zink, .img-rist, .img-start, .img-humat, .img-bor').hover(function() {
   let className = $(this).attr("class").substr(3);
   $('#btn' + className).toggleClass("active");
 });

推荐阅读