首页 > 解决方案 > 如何运行javascript减少功能?

问题描述

我正在尝试编写一个javascript,我通过使用它的id从p标签中获取内部HTML,然后reduce在它上面应用一个javascript函数,这样如果index属于values那么span应该word selected作为类类,否则如果index不属于values那么span应该只有word作为类

这是 p 标签

<p id="content">Sun rises in east</p>

const html_create_fn = () => {
    let values = ["2","3"]
    let sentence = document.getElementById("content") ? document.getElementById("content").innerHTML : null
    console.log(sentence);
    let words = sentence ? sentence.split(" ") : null
    console.log(words);

    if(words){
        document.getElementById("answer_content").innerHTML = words.reduce((acc, word, index) => {
            return `values.includes(${index+1}) ? ${acc}<span class="word selected" id=${index+1}>${word}</span> : ${acc}<span class="word" id=${index+1}>${word}</span>`;
        }, "");
    }
}

所需的输出就像

<p><span class="word">Sun<span><span class="word selected">rises<span><span class="word selected">in<span><span class="word">east<span></p>

当程序运行时,浏览器选项卡被挂起并且它不起作用,我不明白我做错了什么。

标签: javascript

解决方案


我认为您对reduce函数中的字符串插值完全感到困惑。此外,values如果您要使用index.

这(我认为)做你想做的事

const html_create_fn = () => {
    let values = [3,4]
    let sentence = document.getElementById("content") ? document.getElementById("content").innerHTML : null
    console.log(sentence);
    let words = sentence ? sentence.split(" ") : null
    console.log(words);

    if(words){
        document.getElementById("answer_content").innerHTML = words.reduce((acc, word, index) => {
            return acc + (values.includes(index) ? `<span class="word selected" id=${index+1}>${word}</span>` : `<span class="word" id=${index+1}>${word}</span>`);
        }, "");
    }
}
html_create_fn()
span.word {
  border:1px solid blue
}

span.word.selected{
  background-color:yellow
}
<div id="content">Hello world foo bar bash bang</div>
<div id="answer_content"></div>


推荐阅读