我創建了一個叫popcorn.js顯示字幕說明的事件監聽功能。我還在事件監聽器之外創建了與popcorn.js無關的函數,並聲明瞭全局變量數組。我想打印陣列結果(c.innerHTML = subtitleArray [0] [2])在事件監聽器,但它顯示出即使它已存儲在陣列空字符串。請幫忙!爲什麼addEventListener函數無法獲取全局變量?
<html>
<head>
<title>HTML5 included Javascript....</title>
<meta name="description" content="Test" charset="utf-8"></meta>
<script src="popcorn.js"></script>
<script type="text/javascript">
var subtitleArray = new Array(); //stored all values from XML caption file
var firstLine;
var c = document.getElementById('container');
function loadXMLDoc(dname)
{
if (window.XMLHttpRequest)
{
xhttp=new XMLHttpRequest();
}
else
{
xhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.open("GET",dname,false);
xhttp.send();
return xhttp.responseXML;
}
function getCaption()
{
var tempArray = new Array();
captionsDoc = loadXMLDoc("captions.xml");
x=captionsDoc.getElementsByTagName('text');
for(var i=0;i<x.length;i++)
{
var tempArray = new Array();
tempArray[0] = x[i].getAttribute('start'); // get start time
tempArray[1] = x[i].getAttribute('dur'); // get duration time
tempArray[2] = x[i].childNodes[0].nodeValue; // get text
subtitleArray[i] = tempArray; //put all 3 values in array
}
//c.innerHTML = subtitleArray[0][2];
firstLine = subtitleArray[0][2];
}
document.addEventListener("DOMContentLoaded", function() {
var popcorn = Popcorn("#video");
c.innerHTML = subtitleArray[0][2];
popcorn.subtitle({
start: 0,
end: 3,
text: "Hello World", // "Hello World" replace to subtitleArray[0][2]
target: "text"
}).subtitle({
start: 3,
end: 6,
text: "This is second line",
target: "text"
});
popcorn.play();
}, false);
window.onload = getCaption;
</script>
</head>
<body>
<div>
<video id="video" width="320" height="240" controls="true" preload="none">
<source src="caption.mp4" type="video/mp4" />
<source src="caption.webm" type="video/webm" />
<source src="caption.ogg" type="video/ogg" />
</video>
</div>
<div id="text" style="width:980px;height:50px;"></div>
<div id="container"></div>
</body>
</html>
阿賈克斯是異步的,所以當您嘗試使用數組,它仍然是空的。 – adeneo 2013-03-26 12:45:10
你的'c'變量在'getCaption'範圍內,而不是全局變量。 – 2013-03-26 12:45:22
把警報在各功能,看看他們是所謂的順序。 – biziclop 2013-03-26 12:46:27