2

我使用 URL 之类的:http ://example.com/videos/GF60Iuh643I 我正在尝试在 iframe 中使用 javascript 来嵌入 youtube 视频:

<iframe width="560" height="315" src="https://www.youtube.com/embed/<script type="text/javascript">
var segment_str = window.location.pathname;
var segment_array = segment_str.split( '/' );
var last_segment = segment_array.pop();
document.write(last_segment); 
</script>" frameborder="0" allow="autoplay; encrypted-media"  allowfullscreen></iframe>

它应该给 src="https://www.youtube.com/embed/GF60Iuh643I"

但相反,javascript 仍未执行,知道如何使其工作吗?

谢谢!

4

1 回答 1

2

试试这个(未测试)。您通过 id 获取 iframe,然后将 src 设置为等于链接 + 最后一段。

<iframe id="videoframe" width="560" height="315" src="" frameborder="0" allow="autoplay; encrypted-media"  allowfullscreen></iframe>

<script type="text/javascript">
var segment_str = window.location.pathname;
var segment_array = segment_str.split( '/' );
var last_segment = segment_array.pop();
document.getElementById('videoframe').src = 'https://www.youtube.com/embed/' + last_segment;
</script>
于 2018-07-19T05:58:34.810 回答