gpt4 book ai didi

javascript - Eloquent Javascript DOM
 操作

转载 作者:行者123 更新时间:2023-12-03 10:19:07 25 4
gpt4 key购买 nike

我正在处理this例子。我的实现如下:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Title of the document</title>
</head>

<body>
<pre>
Text in a pre element
is displayed in a fixed-width
font, and it preserves
both spaces and
line breaks
</pre>

<p> This is here for contrast</p>
<p> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. </p>

<script>

anode = document.body.getElementsByTagName('pre');
re = /and/g;

/*
@param node is a (<pre> in this case) html node
@param keyword is a RegExp
“syntax highlighter” that looks for <pre> tags with a data-language attribute and
crudely tries to highlight the keywords for that language
*/
function highlightCode(node, keywords) {
var text = node.textContent;
node.textContent = ""; // Clear the node

var match, pos = 0;
while (match = keywords.exec(text)) {
var before = text.slice(pos, match.index);
node.appendChild(document.createTextNode(before));
var strong = document.createElement("strong");
strong.appendChild(document.createTextNode(match[0]));
node.appendChild(strong);
pos = keywords.lastIndex;
}
var after = text.slice(pos);
node.appendChild(document.createTextNode(after));
}

highlightCode(anode, re)
</script>

</body>

</html>

当我运行此文件时,我发现没有发生任何操作。使用我的网络检查器我注意到 anode = document.body.getElementsByTagName('pre');可能不会返回 <pre>标签,因为 node.textContent 似乎返回未定义。这是为什么?

最佳答案

document.body.getElementsByTagName('pre'); 返回文档中所有 pre 标记的数组。将其更改为 document.body.getElementsByTagName('pre')[0]; 以使其仅返回第一个 pre 标记。

或者将 highlightCode 的全部内容包含在 for 循环中,使其突出显示文档中的所有 pre 标记:

function highlightCode(node, keywords) {
for (var i = 0; i < node.length; i++) {
var pre = node[i];
var text = pre.textContent;
pre.textContent = ""; // Clear the node
var match, pos = 0;
while (match = keywords.exec(text)) {
var before = text.slice(pos, match.index);
pre.appendChild(document.createTextNode(before));
var strong = document.createElement("strong");
strong.appendChild(document.createTextNode(match[0]));
pre.appendChild(strong);
pos = keywords.lastIndex;
}
var after = text.slice(pos);
pre.appendChild(document.createTextNode(after));
}
}

关于javascript - Eloquent Javascript DOM <pre> 操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29724205/

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