2

我有一个 div ( contenteditable="true"),其中包含一些文本和一些 html。我正在尝试替换整个 div 中的文本,但与某个类的链接除外。

我试过:

$('div#text').contents().not('a.selected').each(function() {
    $(this).html(replace($(this).text()));
});

但似乎$(this).html()是这样null

div的测试内容是'test <a class="selected">test2</a> test3'

作为输出,我想要"test "替换" test3"为 replace() 函数的结果,而 a.selected 中的文本保持不变。

编辑

div中可能还有其他html,可以忽略。如果替换功能将事物切换为大写,这里是所需的输入 ant ouptut :

输入 :'test <a class="selected">test2</a> <a>test3</a>'

输出:'TEST <a class="selected">test2</a> TEST3'

编辑 2

这似乎有效,但当 replace() 返回一些 HTML 时无效

$("div#text").contents().not("a.selected").each(function() {
    this.nodeValue = replace(this.nodeValue);
});

演示:http: //jsfiddle.net/ApgEc/2/

4

2 回答 2

1

你的意思是这样的吗?

$("div").contents().not("a.selected").each(function() {
    this.nodeValue = replace(this.nodeValue);
});​

演示:http: //jsfiddle.net/ApgEc/


为了能够在replace函数中插入 HTML,我们需要重写代码:

$("div").contents().map(function() {
    if (!$(this).is("a.selected")) {
        return replace(this.nodeValue);
    }
    return this.outerHTML;
}).appendTo($("div").empty());​

演示:http: //jsfiddle.net/ApgEc/3/

于 2012-10-10T08:29:26.657 回答
1

工作演示

$(function() {
    $('#test').contents().each(function() {
        var $this = $(this);
        if ($this.is('a.selected')) return true;
        if(this.wholeText)
            this.wholeText = replace(this.wholeText);
        else $this.html(replace($this.html()));
    });
});
于 2012-10-10T08:35:39.077 回答