用jquery包装html字符串中的所有图像

时间:2016-11-28 23:50:47

标签: javascript jquery html

环顾四周,找不到任何有帮助的东西

我需要一个函数,用匹配的href替换字符串中的所有图像,然后返回一个字符串。

content = "<html>";
var $content = $(content);
$('img', $content).each(function () {
        $(this).html().replace($(this).html(),'<a href="' + $(this).attr('src') + '" target="_blank" class="thumbnailLink"><img src="' + $(this).attr('src') + '" style="' + $(this).attr('style') +'"></a>')                    
    }); 
    return  $content.html();

2 个答案:

答案 0 :(得分:1)

这是可能的解决方案,希望它对您有用。

content = '<div class="img"><img src="fjords.jpg" alt="Fjords" width="300" height="200"><div class="desc">Add a description of the image here</div></div><div class="img"><img src="forest.jpg" alt="Forest" width="300" height="200"><div class="desc">Add a description of the image here</div></div><div class="img"><img src="lights.jpg" alt="Northern Lights" width="300" height="200"><div class="desc">Add a description of the image here</div></div><div class="img"><img src="mountains.jpg" alt="Mountains" width="300" height="200"><div class="desc">Add a description of the image here</div></div>';
html = $( content );


$('img',html).each(function () {
$(this).wrap('<a href="' + $(this).attr('src') + '" target="_blank" class="thumbnailLink"> </a>');    

    }); 
final=[];
$.each(html, function(index, value) {
    final.push($(value).html());
}); 

console.log(final.join(''));

因此,简单地在$ content中包装图像,然后遍历对象,从值创建jQuery对象,获取html(),并输出最终字符串。

DEMO&GT; https://jsfiddle.net/vaxL8d9p/1/

答案 1 :(得分:0)

您可以设置html而不是阅读和替换它。

$('img', $content).each(function () {
    var src = $(this).attr('src');
    var style = $(this).attr('style');
    $(this).html('<a href="' + src + '" target="_blank" class="thumbnailLink"><img src="' + src + '" style="' + style +'"></a>'); 
});