javascript - 使用 jquery 将所有图像包装在 html 字符串中

标签 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();

最佳答案

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

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(),并输出最终字符串。

演示> https://jsfiddle.net/vaxL8d9p/1/

关于javascript - 使用 jquery 将所有图像包装在 html 字符串中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40855521/

相关文章:

jquery - 使用 JQuery 调用 WebMethod

javascript - 如果单击其他元素,是否删除类?

html - 滚动条未隐藏在 Android chrome 中

html - Bootstrap 列顺序

javascript - 如何 append 一些代码并使其与已加载的 js 一起工作?

javascript - 使用 ngStorage 进行 Protractor 测试

javascript - 删除类后 CSS 转换不起作用

javascript - 如何将2d数组从JavaScript传递到ejs中的脚本标签?

javascript - 在 uploadify 中动态设置属性

javascript - 任务的Grunt设置选项,并使用新值运行该任务