1

例如,我有这样一段 html:

var html = '<p>Title</p><b>edit me</b><i>remove me</i>';

我想更改其中的标题,但不想为此使用正则表达式或字符串替换函数,因为如果标题与标签名称匹配,则 html 可能已损坏。

我现在尝试为此采用 jQuery,因为它看起来很有能力,但实际上事情并不那么容易。这是代码:

$( $(html)[0] ).text('New title');
console.log(html); // --> prints out original html with old title

如果可能的话,知道如何使这段代码工作吗?

4

1 回答 1

3
html = $('<div/>').html(html).find('p').text('New title').end().html();

http://jsfiddle.net/bEUHN/

注意:使用创建的 jQuery 对象中有 3 个包装元素$(html),用于选择p您应该使用filter方法的元素。

$(html).filter('p').text('New title'); 
于 2013-04-23T08:50:57.820 回答