Задать вопрос
SecurityYourFingers
@SecurityYourFingers
I make other things, but i know that without your

Как сделать код короче?

Как можно сократить этот код?
$('#button1').hover(function () {
    $('#card1').fadeIn();
}, function () {
    $('#card1').fadeOut();
});
$('#button2').hover(function () {
    $('#card2').fadeIn();
}, function () {
    $('#card2').fadeOut();
});
$('#button3').hover(function () {
    $('#card3').fadeIn();
}, function () {
    $('#card3').fadeOut();
});
  • Вопрос задан
  • 120 просмотров
Подписаться 1 Простой Комментировать
Решение пользователя 0xD34F К ответам на вопрос (2)
0xD34F
@0xD34F Куратор тега JavaScript
const getCard = button => $(`#card${button.id.match(/\d+/).pop()}`);

$('[id^="button"]').hover(
  e => getCard(e.target).fadeIn(),
  e => getCard(e.target).fadeOut(),
);

или

const $buttons = $('[id^=button]').hover(function(e) {
  this.eq($buttons.index(e.target))[e.type === 'mouseenter' ? 'fadeIn' : 'fadeOut']();
}.bind($('[id^=card]')));
Ответ написан
Комментировать