我坚持以下。我有一个播放按钮。当用户第一次点击它时,它应播放歌曲并为其添加暂停按钮。第二次单击按钮时,它应该暂停歌曲。
想出了这个:
$('.play').click(function(event) {
event.preventDefault();
var trackID = $(this).closest('li').attr('data-id');
console.log(trackID);
$('#playlist li').removeClass('active');
$(this).parent().addClass('active');
if ( $(this).hasClass('play pause') ) {
console.log('false');
$(this).removeClass('pause');
} else {
console.log('true');
$(this).addClass('pause');
//return false;
}
if (nowPlaying) {
nowPlaying.stop();
}
SC.stream('/tracks/' + trackID, function(sound) {
if ( !$(this).hasClass('play pause') ) {
console.log('hellooo');
sound.play();
nowPlaying = sound;
} else {
console.log('byeee');
sound.pause();
nowPlaying = sound;
}
});
});
以上部分将正常工作。播放是按钮的默认设置。点击console.log
向我发送trackID:91298058
,true,以及流功能中的字符串hellooo
,并播放歌曲。第二次它还会给我trackID 91298058
,false和字符串hellooo
。所以bug就在这里。每当您点击字符串hellooo
时,都会发送到console.log
。 console.log
- byeee
将永远不会被发送,因此永远不会被暂停。
所以简而言之,我希望有一个按钮可以从播放切换到暂停和反转。在播放时,它应播放歌曲:sound.play();
并暂停时应暂停歌曲:sound.pause();
;
有谁知道如何解决这个问题?
答案 0 :(得分:3)
在传递给SC.stream
的回调函数中,$(this)
被重新定义。
您应该将其缓存在附加到click事件的函数中,并在之后使用它。
$('.play').click(function(event) {
event.preventDefault();
var button = $(this);
// the code
SC.stream('/tracks/' + trackID, function(sound) {
if ( button.hasClass('play pause') ) {
console.log('hellooo');
sound.play();
nowPlaying = sound;
} else {
console.log('byeee');
sound.pause();
nowPlaying = sound;
}
});
此外,您只需检查所在的班级pause
,而不是play pause
。
答案 1 :(得分:0)
我想出了以下解决方法:
在click函数中创建一个布尔值并将其命名为bool
。默认值为false;
。
这与@Colin Delhalle的上述代码非常相似。
$('.play').click(function(event) {
event.preventDefault();
var trackID = $(this).closest('li').attr('data-id');
console.log(trackID);
$('#playlist li').removeClass('active');
$(this).closest('li').addClass('active');
var bool = false;
if ( $(this).hasClass('play pause') ) {
console.log('false');
bool = false;
$(this).removeClass('pause');
} else {
console.log('true');
$('#playlist li a').removeClass('pause');
$(this).addClass('pause');
bool = true;
}
if (nowPlaying) {
nowPlaying.stop();
}
SC.stream('/tracks/' + trackID, function(sound) {
if (bool) {
console.log('play');
sound.play();
nowPlaying = sound;
} else {
console.log('pause');
sound.pause();
nowPlaying = sound;
}
});
});
我认为唯一奇怪的是,函数暂停不会暂停歌曲,但是停止它。有人知道为什么吗?
答案 2 :(得分:-2)
你能试着评论一下这条线吗?
SC.stream('/tracks/' + trackID, function(sound) {
if ( !$(this).hasClass('play pause') ) {
console.log('hellooo');
sound.play();
nowPlaying = sound;
} else {
console.log('byeee');
sound.pause();
// nowPlaying = sound;
}
});