Click Loads multiple videos using YOUTUBE Iframe
I have some thumbnails below the main video contain开发者_JAVA百科er. I will like when you click on each thumbnail - the associated video loads and start playing Using the NEW YOUTUBE API IFRAME approach here
Your help or direction will be appreciated
PREVIEW ON JSFIDDLE HERE
PREVIEW LINK UPDATED***
See this fiddle: http://jsfiddle.net/Y9j7R/5/
Run this code on load:
var a = document.getElementsByTagName("a"); //1
for(var i=0; i<a.length; i++){ //2
if(!/#ytplayer/.test(a[i].href)) continue; //3
var link = a[i].innerHTML.match(/\/vi\/([^\/]+)/); //4
if(link) (function(vidId){ //5
a[i].onclick = function(){ //6
player.loadVideoById(vidId); //7
} //8
})(link[1]); //9
}
Detailed explanation of the code
- Select all
<a>(anchor) elements in the document - Loop through these anchors using
for. During each iteration, the "current" anchor is referred througha[i]. - Check whether the
hrefattribute does not (!) contain "#ytplayer" using thetestmethod of the Regular Expression. If this condition is true (ie: thehrefattribute does not contain "#ytplayer"), thecontinuestatement terminates the current iteration, and jumps to the next anchor. - The
innerHTMLproperty of the current anchor is requested. Thematchmethod is used to get the video id. The Regular expression/\/vi\/([^\/]+)/means: match a substring which equals/vi/<any consecutive non-slash chars>, and group<any consecutive non-slash chars>.
When such a substring is found, thelinkvariable has a property1(one), which holds the value of this group. Otherwise,linkequalsnull. - If the
linkvariable is notnull, an anonymousfunctionis created (lines 5-9) and executed (line 9). The first argument of the function will be referenced throughvidId(variable). - Assigns a newly created
functionto theonclickproperty of the current anchor. Assigning a function to theonclickproperty will cause theonclickevent handler to be defined. - Invokes the
loadVideoByIdmethod of theplayerobject (as defined by the YouTube javascript API). - Invokes the function (created at lines 5-9), passing
link[1]as a first parameter.
References
forloops and thecontinuestatement- Creating and calling
functionsin JavaScript - Regular Expressions (RegExp).
testmethod of theRegExpobject- The
matchfunction in conjunction with a Regular expression - The
innerHTMLproperty of an element - The
onclickevent handler - The
loadVideoByIdmethod of the YouTube JavaScript API
Another interesting answer
- YouTube iframe API: how do I control a iframe player that's already in the HTML?
加载中,请稍侯......
精彩评论