使用jquery替换/操作html字符串中的元素
问题描述:
我有一个html字符串(不是DOM),我想用jquery操作。为什么这不起作用:
I have a html string (not DOM), that I want to manipulate using jquery. Why doesn't this work:
var html = '<div><h4><a class="preview-target" href="content.html">Headline</a></h4></div>';
console.log(html);
var elem = $('h4', $(html));
// replace "Headline" with "whatever" => Doesn't work
elem.replaceWith("whatever");
console.log(html);
I have a jsfiddle here for testing.
上面的代码只是一个简化的例子。真正的html要复杂得多,也就是说,我肯定需要依赖jQuery来操作html字符串。
The above code is just a simplified example. The real html is much more complex, that is, I definitely need to rely on jQuery for manipulating the html string.
答
你修改了jQuery对象,它不会改变字符串文字中的值。
When you modify the jQuery object, it will not change the value in the string literal.
你可以使用
var html = '<div><h4><a class="preview-target" href="content.html">Headline</a></h4></div>';
console.log(html);
var $html = $('<div />',{html:html});
// replace "Headline" with "whatever" => Doesn't work
$html.find('a').html("whatever");
console.log($html.html());
演示:小提琴