简体   繁体   中英

How can I shorten this function (addClass, attr)

How can I shorten the following code, while t1 and $('#t1') are not the same objects?

k1.hover(function(){
    $('#k1').addClass('hovered');
}, function(){
    $('#k1').removeClass('hovered');
});

k2.hover(function(){
    $('#k2').addClass('hovered');
}, function(){
    $('#k2').removeClass('hovered');
});

k3.hover(function(){
    $('#k3').addClass('hovered');
}, function(){
    $('#k3').removeClass('hovered');
});

k4.hover(function(){
    $('#k4').addClass('hovered');
}, function(){
    $('#k4').removeClass('hovered');
});

k5.hover(function(){
    $('#k5').addClass('hovered');
}, function(){
    $('#k5').removeClass('hovered');
});

I am think about something like this:

var magictrick = k[number].hover(function(){
  $('#k[number]').addClass('hovered');
}, function(){
  $('#k[number]').removeClass('hovered');
});

magicktrick[1,2,3,4,5,6,7,8,9];

Is that possible?

// t1 hover
$('#t1').hover(function(){
    t1.attr({fill: '#8b2332'}).addClass('hovered');
}, function(){
    t1.attr({fill: '#e6e6e6'}).removeClass('hovered');
});


// t2 hover
$('#t2').hover(function(){
    t2.attr({fill: '#8b2332'}).addClass('hovered');
}, function(){
    t2.attr({fill: '#e6e6e6'}).removeClass('hovered');
});

I don't see any way you could simplify it more. Just make it more readable.

Maybe you could improve your loop.

var rsrHoversRed = [t1, t2, t3, t4];

for (var i = 0, len = rsrHoversRed.length; i <= len; i++) {
  var el = $(rsrHoversRed[i]);

  el.hover(function(){
      this.attr({
        cursor: 'pointer',
        fill: '#8b2332',
      }).addClass('hovered');
      }, function() {
      this.attr({
        fill: '#e6e6e6'
      }).removeClass('hovered');
  });
}

It would remove your tx.hover(func.. code.

Just another option:

//////////////////////////
// bind both hovers
$('li').hover(function() {
if($(this).attr("id") == "t1") {
  t1.attr({
    fill: '#8b2332'
  });
}
if($(this).attr("id") == "t2") {
  t2.attr({
    fill: '#8b2332'
  });
}
if($(this).attr("id") == "t3") {
  t3.attr({
    fill: '#8b2332'
  });
}
if($(this).attr("id") == "t4") {
  t4.attr({
    fill: '#8b2332'
  });
}
}, function() {
  t1.attr({
    fill: '#e6e6e6'
  });
  t2.attr({
    fill: '#e6e6e6'
  });
  t3.attr({
    fill: '#e6e6e6'
  });
  t4.attr({
    fill: '#e6e6e6'
  });
});

t1.hover(function() {
  $('#t1').toggleClass('hovered');
});

// tn hover

t2.hover(function() {
  $('#t2').toggleClass('hovered');
});

t3.hover(function() {
  $('#t3').toggleClass('hovered');
});

t4.hover(function() {
  $('#t4').toggleClass('hovered');
});

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