我有一个我需要的脚本作为.js文件,所以我可以多次使用它而不需要在任何地方都有多个脚本副本,比如调用脚本YTiFramePlayer.js。但是,也许我想改变promoVideo或videoId。我该怎么做?
//YouTube iframe player
//Load the iframe Player API
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('promoVideo', {
height: '390',
width: '640',
videoId: '00000',
events: {
'onStateChange': onPlayerStateChange
}
});
}
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.STOPPED) {
stopVideo();
}
}
function startVideo() {
$("#video").css("height", "calc(100vh - 48px)");
player.playVideo();
}
function stopVideo() {
player.stopVideo();
$("#video").css("height", "0px");
}
答案 0 :(得分:2)
您可以将此保存为前面提到的.js文件,但将功能包装在您可以在其他位置访问的全局变量中。例如:
script.js:
//YouTube iframe player
//Load the iframe Player API
var ytPlayer = (function() {
var tag = document.createElement('script');
var videoId;
var promoVideo = 'promoVideo';
var player;
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
return {
init(id, promoVideo) {
videoId = id;
promoVideo = promoVideo;
onYouTubeIframeAPIReady();
}
}
function onYouTubeIframeAPIReady() {
console.log('Setting up:', videoId, promoVideo)
player = new YT.Player(promoVideo, {
height: '390',
width: '640',
videoId: videoId,
events: {
'onStateChange': onPlayerStateChange
}
});
}
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.STOPPED) {
stopVideo();
}
}
function startVideo() {
$("#video").css("height", "calc(100vh - 48px)");
player.playVideo();
}
function stopVideo() {
player.stopVideo();
$("#video").css("height", "0px");
}
})();
HTML:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
</head>
<body>
<h1>Hello Plunker!</h1>
<script>
ytPlayer.init('a8a83sda', 'someOtherId')
</script>
</body>
</html>
有关详细信息,请参阅revealing module pattern。
答案 1 :(得分:0)
只需像filename.js扩展名一样保存