HTML:
<div class="youtube-player"></div> <!-- this element will be replaced -->
<button type="button" id="videoBtn1">video 1</button>
<button type="button" id="videoBtn2">video 2</button>
JS:
function loadYouTube(id, title) {
// your config with the parameters id and title
var config = {
repeatPlaylist: 1,
showTime: 1,
height: 356,
toolbar: 'play,prev,next,shuffle,repeat,mute',
// Custom playlist
playlist: {
title: 'Random videos',
videos: [{ id: id, title: title }]
}
};
// replace the html element with an empty you-tube plugin html code
$('.youtube-player').replaceWith($('<div class="youtube-player"><div class="youtube-player-video"><div class="youtube-player-object">You need Flash player 8+ and JavaScript enabled to view this video.</div></div></div>'));
// start youtube-plugin
$('.youtube-player').player(config);
}
// click handlers
$('#videoBtn1').click(function() {
loadYouTube('3qQWibGlfb0', 'title 1 goes here');
});
$('#videoBtn2').click(function() {
loadYouTube('b8MhLvjoBTs', 'title 2 goes here');
});
另見this example。
=== UPDATE ===
把事件處理程序調用到按鈕的一個onclick屬性,並在JavaScript中刪除:
<button type="button" id="videoBtn1" onclick="loadYouTube('3qQWibGlfb0', 'title 1 goes here');">video 1</button>
<button type="button" id="videoBtn2" onclick="loadYouTube('b8MhLvjoBTs', 'title 2 goes here');">video 2</button>
另見the updated example。
=== UPDATE ===
也許這個免費;-)例子可以幫助你:
HTML:
<div id="youtube-player">
<div class="youtube-player-video">
<div class="youtube-player-object">
You need Flash player 8+ and JavaScript enabled to view this video.
</div>
</div>
</div>
<button type="button" id="videoBtn1" onclick="loadYouTube('3qQWibGlfb0', 'title 1 goes here');">video 1</button>
<button type="button" id="videoBtn2" onclick="loadYouTube('b8MhLvjoBTs', 'title 2 goes here');">video 2</button>
JS:
var player = null;
var playlist = {
title: 'Random videos',
videos: []
};
function loadYouTube(id, title) {
// check if player isn't already loaded
if (typeof $('#youtube-player').data('jquery-youtube-player') == 'undefined') {
// add video to playlist
playlist.videos.push({id: id, title: title});
// load player
player = $('#youtube-player')
.show()
.player({
repeatPlaylist: 1,
showTime: 1,
height: 356,
toolbar: 'play,prev,next,shuffle,repeat,mute',
playlist: playlist
});
}
// if player is active
else {
var bFound = false;
// search if video is already in playlist
for (var i = 0; i < playlist.videos.length; i++) {
if (playlist.videos[i].id == id) {
bFound = true;
break;
}
}
if (!bFound) {
// add video to playlist
playlist.videos.push({id: id, title: title});
// load updated playlist
player.player('loadPlaylist', playlist);
}
// show current video
player.player('cueVideo', id);
}
}
另請參閱這updated jsfiddle。
感謝您的回覆。對此,我真的非常感激。我一直堅持這幾天,你的代碼示例會幫助我很多。是否有可能移動JS以外的handels?並使用html輸入youtube id和標題? – user1210772 2012-02-16 08:30:49
我已經更新了我的答案。 – scessor 2012-02-16 09:06:48
謝謝!你以前使用過這個插件嗎? – user1210772 2012-02-16 09:24:00