我使用' video.js'作为外部JavaScript文件。如您所见,此文件中必须提供videoID
。但我想从我的HTML文件中传递这个值,因此我不需要在HTML中包含所有JavaScript。
JavaScript(另存为video.js):
function onYouTubeIframeAPIReady() {
var player;
player = new YT.Player('playVid', {
videoId: 'HERE COMES THE VIDEO ID', // YouTube Video ID
width: 640, // Player width (in px)
height: 360, // Player height (in px)
playerVars: {
autoplay: 1, // Auto-play the video on load
controls: 1, // Show pause/play buttons in player
showinfo: 0, // Hide the video title
modestbranding: 1, // Hide the Youtube Logo
loop: 1, // Run the video in a loop
fs: 0, // Hide the full screen button
cc_load_policy: 0, // Hide closed captions
iv_load_policy: 1, // Hide the Video Annotations
autohide: 0 // Hide video controls when playing
},
events: {
onReady: function(e) {
e.target.mute();
}
}
});
}
HTML
<html>
<head>
<script type="text/javascript" async src="https://www.youtube.com/iframe_api"></script>
<script type="text/javascript" src="video.js"></script>
</head>
<body>
<div id="playVid"></div>
</body>
</html>
这很完美,但我的问题再次出现:
如何在我的HTML中加入videoID
,而其余(JavaScript)代码保留在外部JavaScript文件(video.js)中。
答案 0 :(得分:0)
<html>
<head>
</head>
<body>
<div id="playVid"></div>
<script>
var youtubVideoId = 'YOUR_VIDEO_ID';
</script>
<script type="text/javascript" async src="https://www.youtube.com/iframe_api"></script>
<script type="text/javascript" src="video.js"></script>
</body>
</html>
很确定会这样做。然后只需引用video.js
文件中的JS变量。
function onYouTubeIframeAPIReady() {
var player;
player = new YT.Player('playVid', {
videoId: youtubVideoId, // YouTube Video ID
});
}
答案 1 :(得分:0)
你只需要在你的html中创建一个javascript var。在.js文件中,您只需使用您创建的var。 像这样:
function onYouTubeIframeAPIReady() {
var player;
player = new YT.Player('playVid', {
videoId: myVideoIdVar, // YouTube Video ID
width: 640, // Player width (in px)
height: 360, // Player height (in px)
playerVars: {
autoplay: 1, // Auto-play the video on load
controls: 1, // Show pause/play buttons in player
showinfo: 0, // Hide the video title
modestbranding: 1, // Hide the Youtube Logo
loop: 1, // Run the video in a loop
fs: 0, // Hide the full screen button
cc_load_policy: 0, // Hide closed captions
iv_load_policy: 1, // Hide the Video Annotations
autohide: 0 // Hide video controls when playing
},
events: {
onReady: function(e) {
e.target.mute();
}
}
});
}
<html>
<head>
<script type="text/javascript" async src="https://www.youtube.com/iframe_api"></script>
<script type="text/javascript">
var myVideoIdVar = 'HERE COMES THE VIDEO ID'
</script>
<script type="text/javascript" src="video.js"></script>
</head>
<body>
<div id="playVid"></div>
</body>
</html>