环顾四周,找不到任何有用的东西
我需要一个函数,用匹配 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(),并输出最终字符串。
关于javascript - 使用 jquery 将所有图像包装在 html 字符串中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40855521/