我有一个小脚本我正在使用YoutubeAPI,现在每当我发送id
replace
函数时我都无法正常工作。我得到的视频ID正确到我的视频功能但不知何故它对我不起作用。我只想用我要保留的视频替换网址'您好,这是一个帖子'。
我有http://jsfiddle.net/pb6e7ynh/
上的脚本<script src="https://www.youtube.com/iframe_api"></script>
<span id=msg>
Hello this is a post
https://www.youtube.com/watch?v=eLaNBbKJPfw
</span>
jQuery(function($){
$('#msg').html(function(i, html) {
function video(id){
var player;
console.log(id);
player = new YT.Player('msg', {
height: '174',
width: '309',
videoId: id, // videoId: 'eLaNBbKJPfw'
playerVars: {
enablejsapi: 1,
//controls: 0,
disablekb: 1,
fs: 0,
iv_load_policy: 3,
modestbranding: 1,
rel: 0,
showinfo: 0
}
});
}
test = html.replace(/(?:http|https:\/\/)?(?:www\.)?(?:youtube\.com|youtu\.be)\/(?:watch\?v=)?(.+)/g, '$1');
video(test);
});
});
答案 0 :(得分:0)
您应该使用其他元素来创建YouTube播放器(请参阅Fiddle),因为API会将其替换为iframe
<强> HTML 强>
<script src="https://www.youtube.com/iframe_api"></script>
<span id="msg">
Hello this is a post
</span>
<br>
<span id="youtube">
https://www.youtube.com/watch?v=eLaNBbKJPfw
</span>
<强> JS 强>
function video(id){
var player;
console.log(id);
player = new YT.Player('youtube', {
height: '174',
width: '309',
videoId: id, // videoId: 'eLaNBbKJPfw'
playerVars: {
enablejsapi: 1,
//controls: 0,
disablekb: 1,
fs: 0,
iv_load_policy: 3,
modestbranding: 1,
rel: 0,
showinfo: 0
}
});
}
$(function(){
var html, youtubeID;
html = $("#youtube").html();
youtubeID = html.split("=")[1];
video(youtubeID);
});
更高级一点: Fiddle