jQuery - 用text加上html元素替换文本

时间:2014-04-14 15:58:11

标签: javascript jquery

我希望使用jquery重新编写一些文本。问题是,这个文本不属于它自己的元素,内容是动态的,我无法访问HTML标记以使事情变得更容易。

我可以检测并替换有问题的文本,但我只设法用新的文本节点替换它,因此它将我的html标记视为文本而不是标记

DEMO http://jsfiddle.net/XvTgP/

$('div.myDiv').contents().filter(function () {
    return this.nodeType == 3
}).each(function () {
    this.textContent = this.textContent.replace('my old text no in its own element', '<div class="newClass">my new text</div>');
    var myNewNode = this.textContent;
    return
});

当前输出为文本

<div class="newClass">my new text</div>

3 个答案:

答案 0 :(得分:1)

只需使用replaceWith()

将textNode替换为DIV
$($('div.myDiv div').get(0).nextSibling).replaceWith('<div class="newClass">my new text</div>');

FIDDLE

答案 1 :(得分:0)

在分配HTML内容时尝试添加html

$('div.myDiv').contents().filter(function () {
    return this.nodeType == 3
}).each(function () {
    this.textContent.html = this.textContent.replace('my old text no in its own element', '<div class="newClass">my new text</div>');
    var myNewNode = this.textContent;
    return
});

我认为你可以简化一点:

$('div.myDiv').contents().filter(function () {
    return this.nodeType == 3
}).each(function () {
    this.html(this.textContent.replace('my old text no in its own element', '<div class="newClass">my new text</div>'));
});

这是一个表明它有效的小提琴:http://jsfiddle.net/XvTgP/5/

答案 2 :(得分:0)

如果我正确理解问题

$('div.myDiv').contents().filter(function () {
    return this.nodeType == 3
}).each(function () {
    this.textContent = this.textContent.replace('my old text no in its own element', '<div class="newClass">my new text</div>');
    var myNewNode = this.textContent;
    var myParentNode = myNewNode.parent();
    myParentNode.append(myNewNode);
    return
});