对于一个学校项目,我正在开发一个网站,以使用户彼此倾听。
到目前为止,我有这个按钮,它将使用户能够收听另一位用户正在收听的歌曲,包括正确的位置。但这只会调用一次此函数。
我想要的是[randomNummer}更改时,它将自动再次调用该函数。有谁知道我该怎么做以及实现该目标所需要使用的东西?
这是按钮的代码:
document.getElementById('play-song').addEventListener('click', function() {
$.ajax({
url: 'https://api.spotify.com/v1/me/player/play',
type: 'PUT',
headers: {
'Authorization': 'Bearer ' + access_token
},
dataType: "json",
contentType: "application/json",
data: JSON.stringify({
"uris": [randomNummer],
"position_ms": seconds
})
});
}, false);
randomNummer当前使用数组生成:
var randomNummer;
var myArray = [
"spotify:track:1EtcyegB7JLkAwwqiPyeJ6",
"spotify:track:6rAXHPd18PZ6W8m9EectzH",
"spotify:track:5qaEfEh1AtSdrdrByCP7qR",
"spotify:track:1CnPYaKxTVb4LWOtiGOm0m",
"spotify:track:3qEg6xYffvuvwpq4U6FRrK"
];
setInterval(function(){
callItem();
}, 200000);
var callItem = function(){
randomNummer = myArray[Math.floor(Math.random()*myArray.length)];
document.getElementById("song-uri").innerHTML = randomNummer;
}
答案 0 :(得分:1)
我看到您使用了Jquery。所以...
首先,请更改您的代码:
$('#play-song').on('click', function(e) {
$.ajax({
url: 'https://api.spotify.com/v1/me/player/play',
type: 'PUT',
headers: {
'Authorization': 'Bearer ' + access_token
},
dataType: "json",
contentType: "application/json",
data: JSON.stringify({
"uris": $("#song-uri").val(),
"position_ms": seconds
})
});
}, false);
并且:
var randomNummer;
var myArray = [
"spotify:track:1EtcyegB7JLkAwwqiPyeJ6",
"spotify:track:6rAXHPd18PZ6W8m9EectzH",
"spotify:track:5qaEfEh1AtSdrdrByCP7qR",
"spotify:track:1CnPYaKxTVb4LWOtiGOm0m",
"spotify:track:3qEg6xYffvuvwpq4U6FRrK"
];
setInterval(function(){
callItem();
}, 200000);
var callItem = function(){
randomNummer = myArray[Math.floor(Math.random()*myArray.length)];
$("#song-uri").val(randomNummer);
}
在这种情况下,我们将使用隐藏的输入来存储随机数:
<input type="hidden" id="song-uri" />
最后赶上变更事件:
$("#song-uri").on('change', function(e){
//event on change random value
});
答案 1 :(得分:0)
var randomNummer = {
value: function value(newValue) {
// if a new value is set, assign it to the internal "_value" and trigger the callback which can do stuff as you want
if (typeof newValue !== "undefined") {
this._value = newValue;
this.callback();
}
// always return the current value
return this._value;
},
callback: function callback() {
// do the stuff you want to do after value alters
console.log("Value altered to " + this._value);
}
};
var myArray = [
"spotify:track:1EtcyegB7JLkAwwqiPyeJ6",
"spotify:track:6rAXHPd18PZ6W8m9EectzH",
"spotify:track:5qaEfEh1AtSdrdrByCP7qR",
"spotify:track:1CnPYaKxTVb4LWOtiGOm0m",
"spotify:track:3qEg6xYffvuvwpq4U6FRrK"
];
var callItem = function() {
document.getElementById("song-uri").innerHTML = randomNummer.value(myArray[Math.floor(Math.random()*myArray.length)]);
}
setInterval(callItem, 2000);
<div id="song-uri"></div>
变量有点笨。但是,如果您不直接分配新值而是使用函数,则可以给他们一些控制权。