我在函数中有一个函数,但我无法通过变量。 我正在使用jQuery和Parse.com 这是我的代码:
<script>
$(document).ready(function () {
var tokfile;
Parse.initialize(myApp, myID);
var some_file = Parse.Object.extend("myApp");
var query = new Parse.Query(some_file);
query.equalTo("objectId", "xcxcxcxc");
query.find
({
success: function (results) {
for (var i = 0; i < results.length; i++) {
var object = results[i];
console.log(object.id + ' - ' + object.get('some_file'));
var myObject = object.get('some_file');
var myFile = myObject._url
}
},
error: function (error) {
alert("Error: " + error.code + " " + error.message);
}
});
$("#mp3").attr("src", myFile)
});
</script>
<audio controls preload="none" style="width:480px;">
<source id="mp3" src="placeholder" type="audio/mp3" />
正如您可能看到的那样,我正在尝试将#mp3 id&#s; src更改为我从Parse.com获取的URL 现在由于某种原因我只是无法加载它,而DOM则加载了占位符。 提前谢谢!
答案 0 :(得分:1)
变量的范围是什么,所以将myFile变量放在请求范围之外:
<script>
$(document).ready(function () {
var tokfile;
Parse.initialize(myApp, myID);
var some_file = Parse.Object.extend("myApp");
var query = new Parse.Query(some_file);
var myFile;
query.equalTo("objectId", "xcxcxcxc");
query.find
({
success: function (results) {
for (var i = 0; i < results.length; i++) {
var object = results[i];
console.log(object.id + ' - ' + object.get('some_file'));
var myObject = object.get('some_file');
var audioElement = document.querySelector('#audioplayer');
var source = document.querySelector('#mp3');
source.src = myObject._url;
audioElement.load();
}
},
error: function (error) {
alert("Error: " + error.code + " " + error.message);
}
});
$("#mp3").attr("src", myFile)
});
</script>
<audio controls preload="none" id="audioplayer" style="width:480px;">
<source id="mp3" src="placeholder" type="audio/mp3" />
答案 1 :(得分:0)
修复变量范围没有帮助,您尝试在值存在之前使用该值。
query.find
调用是异步的,因此使用该变量的代码将在将值赋给变量的代码之前运行。
使用回调函数中的值:
query.find
({
success: function (results) {
for (var i = 0; i < results.length; i++) {
var object = results[i];
console.log(object.id + ' - ' + object.get('some_file'));
var myObject = object.get('some_file');
var myFile = myObject._url
$("#mp3").attr("src", myFile)
}
},
error: function (error) {
alert("Error: " + error.code + " " + error.message);
}
});