运行特定事件序列的按钮(我不知道如何简化的详细代码)



我的代码可以工作,但它非常冗长,我知道它可以变得更紧凑。我只是不知道怎么做:-(

我正在构建一个音频组合。单击按钮时,会发生一系列事件。单击另一个按钮时,将终止所有其他活动按钮,并运行该特定按钮的序列。

这些按钮是不可见的,位于开关的可视化中。单击时,切换到"激活"状态的开关图像将删除其"显示:无"类。这应该给用户一种印象,即实际轻弹开关开始播放音频。

这样:

$(function(){
// FIRST BUTTON
$('.button01').click(function() {
if ($('.switch01').hasClass('activated')){
// So if button.button01 is clicked and img.switch01 has class "activated"
// Kill all audio
$('audio').each(function(){ this.pause(); this.currentTime = 0; });
// Turn this switch off
$('.switch01').removeClass('activated');
// Kill all info cards showing the playback controls
$('.audio-info-card').addClass('d-none');
} else { 

// If button.button01 is clicked and img.switch01 DOESN'T have class "activated"
// Turn all other switches off
$('.switch02, .switch03').removeClass('activated');
// Kill all info cards
$('.audio-info-card').addClass('d-none');
// Activate this switch and info card
$('.switch01').addClass('activated');
$('.audio-info-card#card01').removeClass('d-none');
// Kill all audio
$('audio').each(function(){ this.pause(); this.currentTime = 0; });
// Start this audio
$('#audio01-player')[0].play();
}
});
// SECOND BUTTON
$('.button02').click(function() {
if ($('.switch02').hasClass('activated')){ 
// So if button.button02 is clicked and img.switch02 has class "activated"
// Kill all audio
$('audio').each(function(){ this.pause(); this.currentTime = 0; });
// Turn this switch off
$('.switch02').removeClass('activated');
// Kill all info card showing the playback controls
$('.audio-info-card').addClass('d-none');
} else { 

// If button.button02 is clicked and img.switch02 DOESN'T have class "activated"
// Turn all other switches off
$('.switch01, .switch03').removeClass('activated');
// Kill all info cards
$('.audio-info-card').addClass('d-none');
// Activate this switch and info card
$('.switch02').addClass('activated');
$('.audio-info-card#card02').removeClass('d-none');
// Kill all audio
$('audio').each(function(){ this.pause(); this.currentTime = 0; });
// Start this audio
$('#audio02-player')[0].play();
}
});

有16个按钮。我意识到这段代码很愚蠢,但 JS/jQuery 不是我的强项:-D

幸运的是,代码有效,但任何帮助使其更简单将不胜感激!

您可以为所有类名以button开头的按钮分配click()事件,如下所示:

$('button[class^="button"]').click(function() {
let buttonNr = $(this).attr("class").substr(6);
if ($('.switch' + buttonNr).hasClass('activated')) {
$('audio').each(function() {
this.pause();
this.currentTime = 0;
});
$('.switch' + buttonNr).removeClass('activated');
$('.audio-info-card').addClass('d-none');
} else {
$('[class^="switch"]').removeClass('activated');
$('.audio-info-card').addClass('d-none');
$('.switch' + buttonNr).addClass('activated');
$('.audio-info-card#card' + buttonNr).removeClass('d-none');
$('audio').each(function() {
this.pause();
this.currentTime = 0;
});
$('#audio' + buttonNr + '-player')[0].play();
}
});

最新更新