iframe中的javascript无法正常工作

时间:2018-07-19 05:50:51

标签: javascript iframe

我使用以下网址: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仍未执行, 知道如何进行这项工作吗?

谢谢!

1 个答案:

答案 0 :(得分:1)

尝试一下(未测试)。您可以通过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>