Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用jquery替换html字符串中的所有图像_Jquery_Html - Fatal编程技术网

使用jquery替换html字符串中的所有图像

使用jquery替换html字符串中的所有图像,jquery,html,Jquery,Html,我有一个html字符串,我想从中用figure标记替换所有img标记。这是我的密码 $('img',$(html)).replaceWith(function(){ var figure = '<figure><img src="'+$(this).src+'"><figcaption>'+$(this).attr('alt')+'</figcaption></figure>'; return $(figure); })

我有一个html字符串,我想从中用
figure
标记替换所有
img
标记。这是我的密码

$('img',$(html)).replaceWith(function(){
    var figure = '<figure><img src="'+$(this).src+'"><figcaption>'+$(this).attr('alt')+'</figcaption></figure>';
    return $(figure);
});
$('img',$(html)).replaceWith(function(){
var figure=''+$(this.attr('alt')+'';
返回$(数字);
});
此代码不起作用。我还希望在执行操作后返回生成的html字符串,但replace似乎只返回被替换的元素。那么我该怎么做呢?

$(this).src
不是有效的代码。在本例中,您需要
$(this.attr('src')
或只需
this.src

然而,真正的问题可能是您希望
html
被适当地更改——除非您不是在
html
上使用
replacetwith
,而是在
$(html)
上使用。换句话说,你的HTML字符串没有被改变;您的临时jQuery对象是,然后消失

试着这样做:

var html = /* whatever you want */;
var $html = $(html); // jQuery object

$('img', $html).replaceWith(function () {
    return '<figure><img src="' + $(this).attr('src') + '"><figcaption>' + $(this).attr('alt') + '</figcaption></figure>';
});

html = $html.html(); // update html string, if necessary
var html=/*任何您想要的*/;
var$html=$(html);//jQuery对象
$('img',$html).replaceWith(函数(){
返回“”+$(this.attr('alt')+“”;
});
html=$html.html();//如有必要,更新html字符串

你想更换或包装吗?@ArunPJohny只要能完成工作就行。基本上,我只想在元素中添加所有图像,并使用figure元素重新绘制/包装它们,然后返回htmlstring@NimChimpsky不是复制品。这里的问题是html字符串是动态生成的。我要对绳子动手术,然后把它还给我。我正在使用的代码不起作用。@AkshatJiwanSharma抱歉,没有看到您提供“不起作用”的行为@AkshatJiwanSharma您应该将HTML转换为DOM结构,然后使用DOM操作(因此是dupe),然后(可选)序列化回。从技术上讲不是复制品,但足够接近。@谢谢,更新谢谢@火焰贩子。我只有一个问题。正如一条评论指出的那样,Form my scenario将
wrap
做得更好?
wrap
将添加
,但您仍然需要自己创建
并删除
alt
属性。最后,这段代码可能更简单。