Jquery 替换除链接外的文本

Jquery 替换除链接外的文本,jquery,contenteditable,Jquery,Contenteditable,我有一个div(contenteditable=“true”),其中包含一些html。我试图替换整个div中的文本,除了带有特定类的链接 我试过: $('div#text').not('a.selected').each(function() { $(this).html = replaceFunction($(this).text)) }); 但是它不能替换任何东西。您不想设置.html,因为它是由jQuery定义的函数。使用 $('#text :not(a.selected)').

我有一个div(
contenteditable=“true”
),其中包含一些html。我试图替换整个div中的文本,除了带有特定类的链接

我试过:

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

但是它不能替换任何东西。

您不想设置
.html
,因为它是由jQuery定义的函数。使用

$('#text :not(a.selected)').each(function() {
  $(this).html(replaceFunction($(this).text())));
});
编辑:我还注意到您使用了
.text
作为值,但这也是一个函数。我在上面修改了它,调用
.text()
,而不是将其作为字符串处理


EDIT2:另外,您的选择器不正确,已在上面修复
div#text
可以是
#text
,因为您不应该在页面上为另一个元素使用id
text
两次

您的选择器永远不会返回任何内容。您的意思是“在id=text的div不是class=selected的a元素的情况下,给它一个div”。使用
.children()
获取div的子级

.html
.text
是方法。你不能分配给他们。它们具有用于获取和设置的重载:
.html()
将获取html。
.html(newhtml)
将设置html

你想要这样的东西:

$('div#text').children().not('a.selected').each(function() {
    $(this).html(replaceFunction($(this).text()));
});
试试这个

$(this).html(replaceFunction($(this).text())));
您没有设置div的html。。但你似乎只是给它赋值。。这没什么用


代码中也缺少
()
.text()

,jQuery将找到ID为“text”(有一个)的所有div,然后将从结果集中删除所有类为“selected”(没有)的锚元素

如果在div#text中,所有内容都被包装在任何类型的元素中,请尝试以下方法:

$('div#text').children().not('a.selected').each(function() {
    $(this).html = replaceFunction($(this).text))
});
或者性能较差,但所有级别都可以找到

$('div#text').find("*").not('a.selected').each(function() {
    $(this).html = replaceFunction($(this).text))
});

您还可以在一个简单的循环中使用vanilla JS扫描所有HTML节点(包括文本节点)。

对HTML()和text()感到抱歉,我写得太快了:)
$('div#text').children().not('a.selected')
可以简化为
$('a.text>:not(a.selected)
它应该用于文本节点吗$('div#text>:not(a.selected)')。each()不进入each()的内部