简体   繁体   中英

jquery optimize ,repeated use of this

I am using the same variables for mouseover and mouseout,is there any way to shorten this?

 $('#service_tab li').on('mouseover', function() { var $a = $(this).find("a"), dt = $a.attr("href"); $(dt).addClass('tabv'); $("#tabs-1").addClass('tabh'); }); $('#service_tab li').on('mouseout', function() { var $a = $(this).find("a"), dt = $a.attr("href"); $(dt).removeClass('tabv'); $("#tabs-1").removeClass('tabh'); }); 

Use event.type .

$('#service_tab li').on('mouseover mouseout', function (e) {
    var $a = $(this).find("a"),
    dt = $a.attr("href");
    if (e.type == 'mouseover') {
        $(dt).addClass('tabv');
        $("#tabs-1").addClass('tabh'); 
    } else {
        $(dt).removeClass('tabv');
        $("#tabs-1").removeClass('tabh');
    }
});

Yes you can use just one function instead of repeat your code. See the example below.

$('#service_tab li').on('mouseover', function() {
  myFunction('mouseover');
});

$('#service_tab li').on('mouseout', function() {
  myFunction('mouseout');
});

function myFunction(value){
  var $a = $(this).find("a"),
  dt = $a.attr("href");

  if(value == 'mouseout'){
    $(dt).removeClass('tabv');
    $("#tabs-1").removeClass('tabh');
  }else{
    $(dt).addClass('tabv');
    $("#tabs-1").addClass('tabh');
  }
}

Or you can use a switch

$('#service_tab li').on('mouseover', function() {
  myFunction('mouseover');
});

$('#service_tab li').on('mouseout', function() {
  myFunction('mouseout');
});

function myFunction(value){
  var $a = $(this).find("a"),
  dt = $a.attr("href");

  switch(value){
    case 'mouseout' : 
      $(dt).removeClass('tabv');
      $("#tabs-1").removeClass('tabh');
      break;
    case 'mouseover': 
      $(dt).addClass('tabv');
      $("#tabs-1").addClass('tabh');
      break;
   }
}

Just like Drow said (thanks), you can also use toggleClass method of jquery.

toggleClass : Add or remove one or more classes from each element in the set of matched elements.

$('#service_tab li').hover(function() {
  var $a = $(this).find("a"),
  dt = $a.attr("href");
  $(dt).toggleClass('tabv');
  $("#tabs-1").toggleClass('tabh');
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM