我有一个jQuery函数,用图像替换两个值内的链接,例如

<div class="comment">
[youtube]http://www.youtube.com/watch?v=T1hf4B5pyjQ&feature=grec_index[/youtube]
random text
</div>

将输出为
<div class="comment"><img width="420" height="315" src="http://i4.ytimg.com/vi/T1hf4B5pyjQ/hqdefault.jpg"></img>
random text
</div>

具有以下功能
var youtubeTag = /\[youtube]https?:\/\/(?:www\.)?youtu(?:be\.com|\.be)\/(?:watch\?v=|v\/)?([A-Za-z0-9_-]+)([a-zA-Z&=;_+0-9*#-]*?)\[\/youtube]/,
    youtubeHTML = '<img width="420" height="315" src="http://i4.ytimg.com/vi/$1/hqdefault.jpg"></img>';
$(".comment").each(function(){
    var $this = $(this);
    $this.html($this.html().replace(youtubeTag, youtubeHTML))
});

我想做的是单击图片,将youtubeHTML替换为youtubeIFRAME,我在下面尝试过此操作,或在JSFIDDLE http://jsfiddle.net/yusaf/uLTzw/28/上查看
var youtubeTag = /\[youtube]https?:\/\/(?:www\.)?youtu(?:be\.com|\.be)\/(?:watch\?v=|v\/)?([A-Za-z0-9_-]+)([a-zA-Z&=;_+0-9*#-]*?)\[\/youtube]/,
    youtubeHTML = '<img width="420" height="315" src="http://i4.ytimg.com/vi/$1/hqdefault.jpg"></img>';
    youtubeIFRAME = '<iframe width="420" height="315" src="http://www.youtube.com/embed/$1?rel=0" frameborder="0" allowfullscreen></iframe>';
$(".comment").each(function(){
    var $this = $(this);
    $this.html($this.html().replace(youtubeTag, youtubeHTML))
});

$("img").click(function(){
    var $this = $(this);
    $this.html($this.html().replace(youtubeHTML, youtubeIFRAME))
});

最佳答案

问题是$1中的youtubeHTML部分不允许处理程序正确替换HTML。

一种快速的解决方案是在data上使用youtubeHTML属性,并将链接存储在那里。然后,只需将$1中的youtubeIFRAME替换为该data属性的值即可。

Here是代码段。

var youtubeTag = /\[youtube]https?:\/\/(?:www\.)?youtu(?:be\.com|\.be)\/(?:watch\?v=|v\/)?([A-Za-z0-9_-]+)([a-zA-Z&=;_+0-9*#-]*?)\[\/youtube]/;
var youtubeHTML = '<img width="420" data-address="$1" height="315" class="youtube" src="http://i4.ytimg.com/vi/$1/hqdefault.jpg"></img>';
var youtubeIFRAME = '<iframe width="420" height="315" class="youtube" src="http://www.youtube.com/embed/$1?rel=0" frameborder="0" allowfullscreen></iframe>';

$(".comment").each(function(){
    var $this = $(this);
    $this.html($this.html().replace(youtubeTag, youtubeHTML));
});

$("img.youtube").click(function(){
    var $this = $(this);
    $this.replaceWith(youtubeIFRAME.replace("$1", $this.attr("data-address")));
});

编辑:如果有人对如何在占位符图像上写一些简短的“单击此处”文本感兴趣,请看一下 here

10-05 20:54
查看更多