【问题标题】:Render text based on an array of words基于单词数组呈现文本
【发布时间】:2021-09-28 06:21:47
【问题描述】:

我正在尝试为数组中的每个单词呈现一个新的跨度,并为每个单词分配一个索引样式值。我正在使用 JavaScript .map 函数来尝试实现这一点,但是文本没有显示在屏幕上。我觉得我只是错过了一些显而易见的东西,但我不确定它是什么。到目前为止,这是我的代码

const dummyData = ["Bebesh", "Bebeshes", "crime", "Bob", "fighters", "Well", "freeze", "controll", "strangth"]


const injectedContent = dummyData.map(word => {
  var newWord = document.createElement("span").style = `--i: ${dummyData.indexOf(word)}`.textContent= word
  console.log(getComputedStyle(newWord))
})

当我尝试 console.log 计算 newWord var 的样式时,我收到以下错误:

'getComputedStyle' on 'Window': parameter 1 is not of type 'Element'.

【问题讨论】:

  • 你不能这样链接。 style 返回样式。在一个语句中创建您的newWord,然后在另一个语句中设置样式。

标签: javascript arrays dom dom-manipulation


【解决方案1】:

Alex Motor检查以下解决方案。

const dummyData = ["Bebesh", "Bebeshes", "crime", "Bob", "fighters", "Well", "freeze", "controll", "strangth"]
 
const injectedContent = dummyData.map((word,i) => {
  var newWord = document.createElement("span"); 
 newWord.setAttribute("style", "background-color:"+i);
 newWord.textContent=`--${i}:${word}`;
  console.log(newWord)
})

【讨论】:

    猜你喜欢
    • 2017-12-18
    • 1970-01-01
    • 2019-12-01
    • 2021-04-27
    • 1970-01-01
    • 2021-05-11
    • 1970-01-01
    • 2019-01-20
    • 1970-01-01
    相关资源
    最近更新 更多