JS根据h1标签中包含的特定文本切换HTML内容



我是一个javascript新手,一直在寻找一个没有乐趣的解决方案。

我想根据H1标签是否包含某些文本来切换某个p标签的内容。我的目标是把这个js放在每一页的准备,当它需要的时候。

我已经想出了"如果"one_answers"否则如果"应该是一个合适的方法,但我愿意接受其他的想法。我试着写一个"switch"语句,但我不知道如何让它工作。

到目前为止,我发现最接近的是……

<h1>This is about Red</h1>
<p id="colour"></p>
<script>
if('h1:contains("Red")'){
document.getElementById("colour").innerHTML = "Red description";
} else if ('h1:contains("Orange")'){
document.getElementById("colour").innerHTML = "Orange description";
} else if ('h1:contains("Green")'){
document.getElementById("colour").innerHTML = "Green description";
} else if ('h1:contains("Blue")'){
document.getElementById("colour").innerHTML = "Blue description";
}
</script>

…但是当H1标签包含其他文本时,p标签的内容不会改变,只有"红色"文本似乎有效。请有人让我知道我在哪里做错了?很多谢谢!

虽然已经有一个公认的答案,但我添加这个是为了展示一种不同的方法,我认为这种方法在将来的使用中更容易扩展。

查找关键字

与可接受的答案类似,使用.includes()是我们如何确定文本中哪个颜色/关键字的方式,但我也喜欢在进行字符串比较时使用.toLowerCase()这样的东西,因为大小写敏感可能导致.includes()这样的东西返回false,如果两个单词的大写方式不相同。

使用对象if/elseswitch()语句可能很有用,但对于涉及多个不同选项的情况,我通常倾向于使用对象或对象数组。对象还使以后的添加和自定义更容易一些。

const h1 = document.querySelector("h1"),
description = document.querySelector("#colour"),
colors = [
{ color: "red", description: "Red description" },
{ color: "orange", description: "Orange description" },
{ color: "green", description: "Green description" },
{ color: "blue", description: "Blue description" }
]

description.innerText = colors.filter(f => h1.innerText.toLowerCase().includes(f.color))[0]?.description
<h1>This is about Red</h1>
<p id="colour"></p>

本质上,这是在对象数组上使用.filter()来查找其color属性在h1元素的文本中找到的任何对象。

扩大/更新

我不知道这个计划的用例是什么,但我假设你最终不会真的想要">红色描述"如果它找到单词">Red";在文本的任何地方。相反,您可能会有一些其他的措辞或句子,它们可以很容易地设置在这个对象中。添加其他颜色就像复制另一种颜色/行并更改文本一样简单。

更新您的评论的答案:

如果你想要一些高级的If语句,你可以使用类似于第一种方法的If语句:

const elH1Content = document.getElementById("h1").innerHTML;
const elColour = document.getElementById("colour");
if (elH1Content) {
if (elH1Content.includes("Red")) {
elColour.innerHTML = "First one (red)";
} else if (elH1Content.includes("Orange")) {
elColour.innerHTML = "Second one (orange)";
} else if (elH1Content.includes("Green")) {
elColour.innerHTML = "Third one (green)";
} else if (elH1Content.includes("Blue")) {
elColour.innerHTML = "Forth one (blue)";
}
}
<h1 id="h1">This is about Blue</h1>
<p id="colour"></p>

我以前没有在JavaScript的if语句中见过'h1:contains("Red")'。你确定那是正确的吗?

你可以得到H1的innerHTML,然后检查如果字符串.includes的颜色字符串。

注意,我给H1元素一个id=" H1 "来直接访问该元素。否则,您需要循环遍历页面上的所有H1元素。

请对h1元素使用选择器,然后使用其内容进行检查。这段代码可以工作。

const h1El = document.getElementById("sel")
if(h1El.textContent.includes('Red')){
document.getElementById("colour").innerHTML = "Red description";
} else if (h1El.textContent.includes('Orange')){
document.getElementById("colour").innerHTML = "Orange description";
} else if (h1El.textContent.includes('Green')){
document.getElementById("colour").innerHTML = "Green description";
} else if (h1El.textContent.includes('Blue')){
document.getElementById("colour").innerHTML = "Blue description";
}

最新更新