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/

相关文章:

javascript - 如何使 JavaScript 在第二次访问页面时激活?

javascript - 如何关注必填字段或无效字段?

javascript - .html() 不返回克隆 DOM 子树的修改版本

javascript - 砌体/动态幻灯片高度问题

jquery - Bootstrap 嵌套 Accordion ,内部 div 不是面板

javascript - 替换jquery中ul的<a>文本

html - 无法让文字漂浮在背景图片上

html - 背景图像和文本水平导航栏

javascript - Angular 无法让 ng-model 在嵌套指令中工作

javascript - 在电子邮件类型的 HTML 输入字段中输入空格时,Chrome 不会触发 onchange 事件