【发布时间】:2016-04-01 18:52:35
【问题描述】:
我的页面上有很多链接,都是在随机的地方写的。如果有这样的链接:
<a href="https://youtu.be/4tG274QuqHM" title="Go To https://youtu.be/4tG274QuqHM" target="_blank" style="text-decoration:none;">https://youtu.be/4tG274QuqHM</a>
或
<a href="https://youtube.com/watch?v=4tG274QuqHM" title="Go To https://youtube.com/watch?v=4tG274QuqHM" target="_blank" style="text-decoration:none;">https://youtube.com/watch?v=4tG274QuqHM</a>
或
Any Other YouTube Video Link Format
在 JavaScript 中有什么方法可以获取任何形式的 YouTube 链接并将其转换为 YouTube 嵌入 iframe,通过使用 JavaScript 使其最终看起来像这样;
<iframe width="420" height="345" src="http://www.youtube.com/embed/4tG274QuqHM?autoplay=0&autohide=1&controls=2&rel=0" frameborder="0" allowfullscreen="true"></iframe>
任何人都可以修复此代码以使其正常工作吗???
$(document).ready(function() {
$('a').each(function() {
var matches = $(this).attr("href").match(/^(?:https?:\/\/)?(?:www\.)?(?:youtu\.be\/|youtube\.com\/(?:embed\/|v\/|watch\?v=|watch\?.+&v=))((\w|-){11})(?:\S+)?$/);
if(matches){
$(this).attr("class","youtube-link");
}
});
$('a.youtube-link').each(function() {
var yt_url = this.href,
yt_id = yt_url.split('?v=')[1],
yt_id = yt_url.split('embed/')[1],
yt_title = $(this).text();
$(this).replaceWith('<iframe style="max-width:560px;max-height:315px;" width="600" height="600" src="http://www.youtube.com/embed/' + yt_id + '?rel=0" frameborder="0" allowfullscreen></iframe>');
});
});
【问题讨论】:
-
是的,这可以使用 JavaScript 完成..
-
您实际尝试过什么?请向我们展示您的 JavaScript 代码以及您希望它做什么。
-
StackOverflow 不是代码编写服务 - 您必须先尝试一些东西,我们才能为您提供帮助。
-
@MathiasBecher 我已经非常努力地尝试了一些 JavaScript,但效果不佳;你能帮我修一下吗???
标签: javascript jquery html youtube