【问题标题】:javascript inside iframe not workingiframe中的javascript不起作用
【发布时间】:2018-07-19 05:50:51
【问题描述】:

我使用 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 仍然未执行, 知道如何完成这项工作吗?

谢谢!

【问题讨论】:

  • 代码中的主要问题是您不能像这样在 iframe 元素中添加 js 脚本

标签: javascript iframe


【解决方案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>

【讨论】:

  • 很高兴,我能帮上忙。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-27
  • 2017-01-10
  • 2018-05-01
  • 2018-11-25
  • 1970-01-01
相关资源
最近更新 更多