使用jquery替换/操作html字符串中的元素
我有一个html字符串(不是DOM),我想用jquery操作。 为什么这不起作用:
var html = ''; console.log(html); var elem = $('h4', $(html)); // replace "Headline" with "whatever" => Doesn't work elem.replaceWith("whatever"); console.log(html);
我在这里有一个jsfiddle进行测试。
上面的代码只是一个简化的例子。 真正的html要复杂得多,也就是说,我肯定需要依赖jQuery来操作html字符串。
修改jQuery对象时,它不会更改字符串文字中的值。
您可以使用
var html = ''; console.log(html); var $html = $('',{html:html}); // replace "Headline" with "whatever" => Doesn't work $html.find('a').html("whatever"); console.log($html.html());
演示: 小提琴
你可以找到h4然后调用replaceWith方法。
var html = $(''); console.log(html.html()); html.find('h4').replaceWith('whatever') console.log(html.html());
的jsfiddle
var html = ''; var replaced=html.replace("Headline","whatever"); console.log(replaced);
试试这个