gpt4 book ai didi

javascript - 使用 JavaScript 为段落中的单词设置背景色 "yellow"

转载 作者:行者123 更新时间:2023-12-05 04:34:52 24 4
gpt4 key购买 nike

为超过 8 个字符的段落中的单词设置背景色“黄色”。

我尝试了下面的 JavaScript 代码,但它显示 Cannot set properties of undefined (setting 'color')

const a=document.querySelector("p");
a.innerHTML=
a.innerText.split(" ")
.map(
function(word){

if (word.length>8){
word.style.color="yellow";
}
else{
return word;
}
}
)

.join(" ");
<h1>Heading</h1>

<!-- this is the paragraph I used-->

<p>Hey, you're not permitted in there. It's restricted. You'll be deactivated for sure.. Don't call me a mindless philosopher, you overweight glob of grease! Now come out before somebody sees you. Secret mission? What plans? What are you talking about? I'm not getting in there! I'm going to regret this. There goes another one. Hold your fire. There are no life forms. It must have been short-circuited. That's funny, the damage doesn't look as bad from out here. Are you sure this things safe?

Close up formation. You'd better let her loose. Almost there! I can't hold them! It's away! It's a hit! Negative. Negative! It didn't go in. It just impacted on the surface. Red Leader, we're right above you. Turn to point... oh-five, we'll cover for you. Stay there... I just lost my starboard engine. Get set to make your attack run.

The Death Star plans are not in the main computer. Where are those transmissions you intercepted? What have you done with those plans? We intercepted no transmissions. Aaah....This is a consular ship. Were on a diplomatic mission. If this is a consular ship...were is the Ambassador? Commander, tear this ship apart until you've found those plans and bring me the Ambassador. I want her alive! There she is! Set for stun! She'll be all right. Inform Lord Vader we have a prisoner.

What a piece of junk. She'll make point five beyond the speed of light. She may not look like much, but she's got it where it counts, kid. I've added some special modifications myself. We're a little rushed, so if you'll hurry aboard we'll get out of here. Hello, sir. Which way? All right, men. Load your weapons! Stop that ship! Blast 'em! Chewie, get us out of here! Oh, my. I'd forgotten how much I hate space travel.

Run, Luke! Run!</p>

最佳答案

也许我们可以尝试使用返回的 span 元素修改 innerHTML。

<script>
const a=document.querySelector("p");
const text = a.innerHTML.split(" ").map(function(word) {
if(word.length > 8) {
return `<span style="color: yellow;">${word}</span>`
} else {
return `<span>${word}</span>`
}
}).join(" ")
a.innerHTML= text
</script>

关于javascript - 使用 JavaScript 为段落中的单词设置背景色 "yellow",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71153244/

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