我想编写一个运行如下的 javascript 函数:
输入:Youtube 视频 ID(即 F3v39wnv)、高度、宽度和名称
Action :弹出一个新窗口,指定宽度和高度,显示指定的视频。
我已经想出了一个基本的方法(通过使用 document.write() ),但我知道这会使页面容易出现漏洞。
我是一个很强的程序员,我只是一点都不熟悉 javascript。将参数传递给新网页的标准方法是什么?我已经能够让源页面生成包含所有指定参数的新窗口,如下所示:videoplayer.htm?vid=(VidID)?height=(height)?width=(width)?name=(name),但我无法从 videoplayer.htm 中读取这些参数
谢谢!
最佳答案
您可以使用 window.location。更具体地说,window.location.pathname 将返回主机名后面的所有内容。在此页面中,这将是“questions/4856801/javascript-video-pop-up-window”
然后您可以使用 String.split 方法将 url 拆分为其参数
var arguments = window.location.pathname.split("?")[1].split("&");
应该将 "videoplayer.htm?vid=3&height=4&width=5"拆分为 ["vid=3", "height=4", "width=5"]
然后用“=”字符进一步拆分每个参数应该给你一个标签=>值数组 "vid=3".split("=") 变成 ["vid", "3"]
function fetchArguments() {
var arg = window.location.pathname.split("?")[1].split("&"), // arguments
len = arr.length, // length of arguments
obj = {}, // object that maps argument id to argument value
i, // iterator
arr; // array
for (var i = 0; i < len; i++) {
arr = arg[i].split("="); // split our first argument
obj[arr[0]] = arr[1]; // e.g. obj["vid"] = "3"
}
return obj;
}
function loadVideo() {
var args = fetchArguments(),
iframe = document.createElement("iframe");
iframe.title = "YouTube video player";
iframe.width = args["width"];
iframe.height = args["height"];
iframe.src = "youtube.com/embed/" + args["vid"];
iframe.type = "text/html";
iframe.className = "youtube-player";
// I'm sure you get the idea
document.getElementsByTagName("body")[0].appendChild(iframe); // we append the iframe to the document's body
}
所以我不确定你到底想用 iframe 做什么,但在我的示例中,loadVideo() 函数将创建一个元素并将其附加到文档的主体
关于Javascript:视频弹出窗口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4856801/