我有一个html字符串,我想img用figure标签替换我的所有标签.这是我的代码
$('img',$(html)).replaceWith(function(){
var figure = '<figure><img src="'+$(this).src+'"><figcaption>'+$(this).attr('alt')+'</figcaption></figure>';
return $(figure);
});
Run Code Online (Sandbox Code Playgroud)
此代码不起作用.我还希望在执行操作后返回生成的html字符串,但似乎replace只返回已替换的元素.那我该怎么做?
$(this).src是无效的代码.你需要$(this).attr('src')或只是this.src在这种情况下.
然而,真正的问题可能是你希望html就地改变-除非你不使用replaceWith的html,但上$(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
Run Code Online (Sandbox Code Playgroud)
http://jsfiddle.net/mblase75/77aXS/