gpt4 book ai didi

javascript - 如何使用 Javascript 修改节点的内容?

转载 作者:行者123 更新时间:2023-11-30 13:43:47 25 4
gpt4 key购买 nike

我需要使用 Javascript 来做三件事:

  1. 选择类别为“foo”的所有节点。
  2. 找到这些节点中以“*”开头的所有单词。
  3. <span class="xyz"> ... </span> 将这些词括起来, 其中xyz是这个词本身。

例如内容:

<ul>
<li class="foo">
*abc def *ghi
</li>
<li class="bar">
abc *def *ghi
</li>
</ul>

会变成

<ul>
<li class="foo">
<span class="abc">*abc</span> def <span class="ghi">*ghi</span>
</li>
<li class="bar">
abc *def *ghi <!-- Not part of a node with class "foo", so
</li> no changes made. -->
</ul>

我该怎么做?(附注,涉及 jQuery 的解决方案也可以工作,但除此之外我不希望包含任何其他依赖项。)

最佳答案

不需要 jQuery:

UE_replacer = function (node) {

// just for performance, skip attribute and
// comment nodes (types 2 and 8, respectively)
if (node.nodeType == 2) return;
if (node.nodeType == 8) return;

// for text nodes (type 3), wrap words of the
// form *xyzzy with a span that has class xyzzy
if (node.nodeType == 3) {

// in the actual text, the nodeValue, change
// all strings ('g'=global) that start and end
// on a word boundary ('\b') where the first
// character is '*' and is followed by one or
// more ('+'=one or more) 'word' characters
// ('\w'=word character). save all the word
// characters (that's what parens do) so that
// they can be used in the replacement string
// ('$1'=re-use saved characters).
var text = node.nodeValue.replace(
/\b\*(\w+)\b/g,
'<span class="$1">*$1</span>' // <== Wrong!
);

// set the new text back into the nodeValue
node.nodeValue = text;
return;
}

// for all other node types, call this function
// recursively on all its child nodes
for (var i=0; i<node.childNodes.length; ++i) {
UE_replacer( node.childNodes[i] );
}
}

// start the replacement on 'document', which is
// the root node
UE_replacer( document );

更新:对比strager's answer的方向,我摆脱了拙劣的 jQuery 并使正则表达式尽可能简单。事实证明,这种“原始”javascript 方法比我预期的要容易得多。

虽然 jQuery 显然很适合操纵 DOM 结构,但要弄清楚如何操纵 text 元素实际上并不容易。

关于javascript - 如何使用 Javascript 修改节点的内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/711895/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com