我想记录一首歌的播放次数。我得到了这个工作,但我不希望在浏览器关闭时重置这么多次。我尝试过使用cookies,但无法解决这个问题。
期待您的回复!
HTML
<!DOCTYPE html>
<html>
<head>
<title>Showcase Titou Brouwers</title>
<meta charset ="UTF-8">
</head>
<body>
<audio id="music" autoplay="autoplay" controls="controls" onended="yourFunction()">
<source src="Data/1.mp3" type="audio/mp3" />
</audio>
<script src="App.js"></script>
<p>Total amount of sessions: </p>
<p id="demo"></p>
</body>
</html>
Javscript
//if music ends perform addSession
document.querySelector("#music").addEventListener("ended", addSession, false);
//Create cookie
document.cookie = "totalSessionsJ=0";
var totalSessions = document.cookie;
console.log(totalSessions);
//Increase totalSessions variable with 1
function addSession () {
document.cookie = totalSessions + 1;
//Display amount of performed sessions
document.getElementById("demo").innerHTML = totalSessions;
}
//Display 0 when no sessions have been performed yet
//document.getElementById("demo").innerHTML = 0;
/*
//If music ends perform yourFunction
document.querySelector("#music").addEventListener("ended", yourFunction, false);
//Let box pup-up in which you can type the score you give your session
function yourFunction () {
prompt('How many stars of five do you give this session?');
}
*/
修改
现在,我有以下内容,但是我在向cookie值添加1时遇到了困难。此外,最后一行代码不想工作。
//Create cookie
document.cookie = "totalSessionsJ=0; expires=Sun, 28 May 2028 12:00:00 UTC";
function getCookieVal() {
var cookieValue = document.cookie.replace(/(?:(?:^|.*;\s*)totalSessionsJ\s*\=\s*([^;]*).*$)|^.*$/, "$1");
return cookieValue;
}
//Increase totalSessions variable with 1
function addSession () {
var test = getCookieVal() + 1;
console.log(test);
document.cookie = "totalSessionsJ = test; expires=Sun, 28 May 2028 12:00:00 UTC";
//Display amount of performed sessions
document.getElementById("demo").innerHTML = getCookieVal();
}
//Display 0 when no sessions have been performed yet
document.getElementById("demo").innerHTML = "getCookieVal()";
答案 0 :(得分:0)
试试这个例子:
myAudio = new Audio('someSound.ogg');
myAudio.addEventListener('ended', function() {
this.currentTime = 0;
this.play();
}, false);
myAudio.play();
答案 1 :(得分:0)
默认情况下,关闭浏览器时会删除cookie。您可以在cookie中添加日期以便在将来设置远期,因此不会删除它:
document.cookie = "totalSessionsJ=0; expires=Sun, 28 May 2028 12:00:00 UTC";
要读取值:
function getCookieVal() {
var cookieValue = document.cookie.replace(/(?:(?:^|.*;\s*)totalSessionsJ\s*\=\s*([^;]*).*$)|^.*$/, "$1");
return cookieValue;
}