我的网站看起来像这样创造的歌曲的播放列表: 媒体播放/暂停切换,而不使用太多的if语句?
不过,我很努力找出实现所有可能的case语句的正确方法,虽然切换,用户可以经历该按钮,如:
- 切换和关闭
- 切换上一个播放按钮,然后点击另一个播放按钮,使以前有关闭同时
- 等一个播放按钮。
现在,我的代码(下图)适用于每种情况,除非用户切换播放按钮的开启和关闭,然后单击不同的播放按钮。此特定情况会导致两个图标切换到暂停按钮,而不是最近单击。我知道为什么会发生这种情况,这是因为在旧的播放按钮上留下了lastPlayed
的ID,因此触发了切换if
陈述。
我的问题是,是否有更简单的方法来设置播放按钮切换,涵盖所有这些情况,而不必为每种可能的结果制定具体的if
声明?
要么寻找更好的解决方案,要么修复我的一个bug,但总是首选更清晰的代码,谢谢任何帮助!
var playCounter = 0;
function clickSongPlay(artist, title, url, imageURL, element) {
//debugger;
player.playlist.push(
{
title: title,
artist: artist,
file: url,
imageURL: imageURL,
howl: null
}
);
//check to see if we need to resume the song
if ($(element).hasClass("resumeSong") && $(".music-control").hasClass("ion-ios-play")) {
console.log("resuming");
/////////LINE BELOW RESUMES THE TRACK FROM CURRENT POSITION////////
player.play();
$(element).toggleClass("ion-ios-play ion-ios-pause");
$(".resumeSong").removeClass("resumeSong");
return;
}
//if a song is playing and the pause button is clicked, pause the track
if ($(element).hasClass("ion-ios-pause")) {
console.log("pausing");
player.pause();
$(element).toggleClass("ion-ios-pause ion-ios-play");
$(element).addClass("resumeSong");
return;
}
//start playing a new song
if ($(element).hasClass("ion-ios-play") && !$(element).hasClass("resumeSong")) {
if ($("#lastPlayed") && !playCounter == 0) {
console.log("here is a new song");
$("#lastPlayed").toggleClass("ion-ios-pause ion-ios-play")
$(".music-control").removeAttr("id", "lastPlayed");
}
console.log("new song");
///////LINE BELOW LOADS THE NEW SONG//////////////
player.skipTo(player.playlist.length - 1);
$(element).toggleClass("ion-ios-play ion-ios-pause");
$(element).attr("id", "lastPlayed");
playCounter += 1;
return;
}
}
这里是一个特定歌曲的div的HTML:
<div><i class="icon ion-ios-play music-control" onclick="clickSongPlay('@song.Artist','@song.Title','@song.URL','@song.Album.ImageURL', this);"></i></div>
如何播放按钮被指定为这样?即是'.music-control'一个CSS类,应用于所有播放按钮? –
@BozhidarStoinev查看我添加的HTML行吗?每首歌曲项目(显示在顶部图片中)都有这些类别。当点击一个播放按钮时,'ion-ios-play'类被切换到'ion-ios-pause',这些是来自Ionicons库的css类。 '.music-control'在每首歌的每个班上。这有帮助吗? –