javascript - 如何将 cookie 的值设置为 0 如果
问题描述
所以,我一直在玩弄这个,我对 JS 感到很糟糕,但我觉得我真的很接近弄清楚它,所以即使只是被指向正确的方向也会有所帮助。
现在,我的音频可以通过 cookie 在页面更改中持续播放,这部分效果很好。但是,当歌曲源更改时,我真的希望歌曲从 0 开始。(现在它只是继续以 cookie 当前持有的值播放。)
这是我到目前为止所拥有的:
var song = document.getElementsByTagName("audio")[0];
var source = song.currentSrc;
var originalSource = source;
var played = false;
var tillPlayed = getCookie("timePlayed");
function update()
{
if(!played){
if(tillPlayed){
if (source == originalSource){
song.currentTime = tillPlayed;
song.play();
played = true;
}
else {
song.currentTime = 0;
cong.currentTime = tillPlayed;
song.play();
played = true;
}
}
else {
song.play();
played = true;
}
}
else {
setCookie('timePlayed', song.currentTime);
}
}
setInterval(update,0);
它只是让歌曲根本无法播放。
看起来它应该是正确的,我现在只是不知道为什么它不起作用。
任何人都有让它发挥作用的任何提示吗?
编辑:我已经将额外的代码移到了原始函数中,这就是我现在所拥有的。它仍然无法正常工作,音乐将再次播放,但不会重置 cookie。
cookie 确实发挥了应有的作用,我只是想改变它
解决方案
看起来您正在将 cookie 中的值分配给 song.currentTime 在重置后立即
song.currentTime = 0;
song.currentTime = tillPlayed;
根据您的整体实现,您可以解决此解决方案变体中的注释中描述的几种方法:
var song = document.getElementsByTagName("audio")[0];/* orgiinal source song of the html player */
var source = getCookie("mySong");
if (source) /* You may different/additional logic for your exact use case*/
song.currentSrc = source /*Set audio player's source */
else
source = song.currentSrc; /*Save audio player source */
var originalSource = source;
var played = false;
var tillPlayed = getCookie("timePlayed");
function update()
{
if(!played)
{
if(tillPlayed)
{
if (source == originalSource) /* Note this this will only detect if the audio has since we came into the page. */
{
song.currentTime = tillPlayed;
song.play();
played = true;
}
else
{
song.currentTime = 0;
/* Since we just reset we do not want to retrieve the existing value in the cookie*/
/* cong.currentTime = tillPlayed; */
setCookie('timePlayed', song.currentTime); /* Store the reset value in the cookie. If the condition at the end is removed, you don't need to do this here. */
setCookie('mySong', song.currentSrc);
song.play();
played = true;
}
}
else
{
song.play();
played = true;
}
}
/* If it does not interfere with existing logic,
consider removing the else and always storing the value in the cookie here.
*/
else
{
setCookie('timePlayed', song.currentTime);
setCookie('mySong', song.currentSrc);
}
}
setInterval(update,0); /* Note that values of < 10ms resolve to 10ms */
希望有帮助