JQuery用新文本替换元素中的任何文本

时间:2011-08-15 14:48:30

标签: jquery replace load

使用JQuery查找特定文本非常容易,但我希望在特定元素中找到任何文本并替换它。我正在使用load()从另一个页面获取一个元素,因此文本会有所不同,这就是为什么我不能依赖于:contains()。

$("#results").load('http://www.test.com/url.html .ms-bodyareaframe .ms-vb-title a', function() {
    ('.ms-vb a').html("New Text");
});

正在加载的元素的html是:

<td class="ms-vb">
<a>
Old Text
</a>
</td>

如果使用函数()在加载中完成文本替换,或者在加载页面后单独完成文本替换,则无关紧要。但我已经尝试了几种方法,但我无法使其发挥作用。

1 个答案:

答案 0 :(得分:0)

这是您可以以可管理的方式查找和替换文本节点中的值的方法:

function findAndReplace(elements, textToFind, textToPlace) {
    $.each(elements.contents(), function () {
        // This is added to make sure the nodes you request are text nodes
        if (this.nodeType == 3)
            this.nodeValue = this.nodeValue.replace(textToFind, textToPlace);
    });
}

findAndReplace($('your element(s)'), 'textToFind', 'textToPlace');