javascript – 使用jquery替换/操纵html字符串中的元素

我有一个html字符串(不是DOM),我想使用 jquery来操作.为什么这不工作:
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);

我有一个jsfiddle here进行测试.

上面的代码只是一个简单的例子.真正的html要复杂得多,也就是说,我绝对需要依靠jQuery来处理html字符串.

解决方法

修改jQuery对象时,不会更改字符串文字中的值.

您可以使用

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());

演示:Fiddle

相关文章

页面搜索关键词突出 // 页面搜索关键词突出 $(function () {...
jQuery实时显示日期、时间 html: &lt;span id=&quot...
jQuery 添加水印 &lt;script src=&quot;../../../.....
中文:Sys.WebForms.PageRequestManagerParserErrorExceptio...
1. 用Response.Write方法 代码如下: Response.Write(&q...
Jquery实现按钮点击遮罩加载,处理完后恢复 思路: 1.点击按...