Why does this javascript work...but this doesn't?
I load everything on my page. At the end, I have this script.
<script type="text/javascript">loadNewVideo('u1zgFlCw8Aw',0)</script>
It doesn't work. But if I substitute it with this, it works.:
<input type="submit" onclick="loadNewVideo('u1zgFlCw8Aw',0);" >
In the .JS file, this is the function:
function loadNewVideo(id, startSeconds) {
alert('In-the-function');
if (ytplayer) {
alert('Found-ytplayer');
ytplayer.loadVideoById(id, parseInt(startSeconds));
开发者_StackOverflow中文版 }
}
Apparently, "ytplayer" is false in the first one!??
I don't know what ytplayer
is, but I imagine this problem has something to do with the DOM not being fully loaded. Have you tried this?
<script type="text/javascript">
$(document).ready(function() {
loadNewVideo('u1zgFlCw8Aw', 0);
});
</script>
edit: If this doesn't work, you will have to give us more information. As Tim and Peter asked you in comments to your question, can you tell us where ytplayer
is defined and what it is? I'm assuming it stands for YouTube Player, maybe it's being loaded/defined after you were calling loadNewVideo
?
For example, if the code snippet above is above the part where ytplayer
is defined in your document, this would still be called before ytplayer
is loaded, depending on how you're loading it. As I said, please supply some more information.
I don't have an answer, but perhaps this will help you figure out when the ytplayer component is ready for use:
var startTimer = new Date().getTime();
function ytplayerReadyCheck() {
var ready = !!ytplayer;
if (!ready) {
window.setTimeout(ytplayerReadyCheck,50);
}
else {
var endTimer = new Date().getTime();
alert('ytplayer is now ready!\n\nWe waited '+(endTimer-startTimer)+' milliseconds for it');
loadNewVideo('u1zgFlCw8Aw', 0);
}
}
ytplayerReadyCheck();
Of course, this is scarcely replacement for figuring out where ytplayer is defined in the first place! Perhaps it's defined in a .js file that's dynamically loaded after the document has loaded?
I'd highly recommend getting hold of Firebug so you can more easily debug this kind of thing.
I would say this is because the DOM hasn't totally loaded at that stage. You want to hook the body onLoad event, or use jQuery to get the $(document).ready() hook.
精彩评论