简化冗余jquery's代码

Simplify redundant jquery's code

本文关键字:代码 冗余 jquery      更新时间:2024-02-16

这是我的jquery代码,工作得很好。

  $(document).ready(function(){
     $(".a").mouseover(function(){
             $("body").addClass("a");    
           });
     $(".a").mouseout(function(){
            $("body").removeClass("a");
        });
     $(".b").mouseover(function(){
             $("body").addClass("b");    
        });
        $(".b").mouseout(function(){
            $("body").removeClass("b");
        });
    $(".c").mouseover(function(){
             $("body").addClass("c");    
            });
    $(".c").mouseout(function(){
            $("body").removeClass("c");
        });
                   ..........etc
                   });
<html>
    <img class="a" src="images/p1.jpg" >
    <img class="c" src="images/p3.png">
    <img class="d" src="images/p4.jpg">
</html>

我想知道是否可以简化它,因为它看起来非常多余。

感谢

在DOMready中,您可以有一个hover处理程序来切换您的类,如下所示:

function onHover() {
    $('body').toggleClass(this.className);
}
$('img[class]').hover(onHover);

注意:鼠标悬停时会触发鼠标的进出。

请看下面的演示或这个小提琴。

function onHover() {
	$('body').toggleClass(this.className);
}
$('img[class]').hover(onHover);
div {
    width: 200px;
    height: 200px;
    background-color: gray;
    margin: 10px;
}
.a {
    background-color: green;
}
.b {
    background-color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img class="a" src="https://placehold.it/300/300" />
<img class="b" src="https://placehold.it/300/300"/>

 <body>
   <img class="a img" data-class="a" src="images/a.jpg">
   <img class="b img img-big" data-class="b" src="images/b.jpg">
   <a href="#nogo" class="a btn btn-external" data-class="a">A link</a>
   <a href="#nogo" class="b btn btn-external" data-class="b">B link</a>
 </body>
$(document).ready(function(){
  $('[data-class]').hover(function(){
    $('body').addClass($(this).data('class'));
  },function(){
    $('body').removeClass($(this).data('class'));
  });
});
 .a { background: red; }
 .b { background-color: blue; }

我使用了一个数据类属性,所以只有所需的类应用于主体。以防万一有多个类应用于悬停的元素。

数据类属性可以应用于任何html标记。

this.className

类似的东西呢:

 $(document).ready(function(){
     $("img").mouseover(function(){
             $("body").addClass(this.className);    
           })
            .mouseout(function(){
               $("body").removeClass(this.className);
            });
     });

您可以从jQuery hover和一些循环中得到一个小的简化。

function bindListeners() {
  var selectors = ['a', 'b', 'c'];
  selectors.forEach(function (selector) {
    $('.' + selector).hover(function () {
      $('body').addClass(selector);
    }, function () {
      $('body').removeClass(selector);
    });
  });
}
$(document).ready(bindListeners);