2013-05-31 40 views
2

我有一个html字符串,我想用figure标记替换所有img标记。这是我的代码使用jquery替换html字符串中的所有图像

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

此代码不起作用。我也想在操作完成后返回生成的html字符串,但看起来replace只返回已被替换的元素。那我该怎么做?

+0

? –

+0

@ArunPJohny无论完成任务。基本上我只想找到元素中的所有图像,然后用空格元素重新包装它们,并返回html字符串 –

+0

@NimChimpsky不是重复的。我在这里遇到的问题是,html字符串是动态生成的。我想要操作字符串然后返回。而我正在使用的代码不起作用。 –

回答

4

$(this).src是无效的代码。在这种情况下,您需要$(this).attr('src')或仅需this.src

然而,真正的问题可能是你期待html就地改变 - 除非你不上html使用replaceWith,但$(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 

http://jsfiddle.net/mblase75/77aXS/

要替换或包裹
+0

或更好this.src –

+0

@roasted谢谢,更新 – Blazemonger

+0

谢谢! @Blazemonger。将在2分钟内接受 –