javascript - 如何运行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>
当程序运行时,浏览器选项卡被挂起并且它不起作用,我不明白我做错了什么。
解决方案
我认为您对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>
推荐阅读
- python-3.x - 使用 shutil.rmtree(dir) 清理安装的 docker 文件夹
- python - 在我的项目中运行单个模块时出现 Python ModuleNotFoundError
- sql - 数据透视表查询上的 Varchar 到 Int 错误
- json - 输入'列表
' 不是类型 'List 的子类型 >? - zabbix - Zabbix:删除不再可发现的主机
- python - 从两个数据帧的两列中的相似值创建新数据帧
- javascript - 使用 Lodash 对对象数组进行分组和求和
- c++ - 是否可以强制通过引用或指针(C++)传递一个类?
- python - 如何根据我的意见而不是基于 Python 中 Pandas 数据框中的某些键来更改索引的顺序?
- python - Python 请求被网站阻止