【问题标题】:change background color of p with javascript depending on result根据结果​​使用javascript更改p的背景颜色
【发布时间】:2018-12-29 20:36:04
【问题描述】:

我需要更改 p 标签中结果的背景颜色,如果变量的结果 > 则为 1。 我想这可以通过 if 语句来完成? 这是我正在使用的代码:

const todos = [{
  text: 'Order airline tickets',
  completed: false
},{
  text: 'Vaccine appointment',
  completed: true
}, {
  text: 'Order Visa',
  completed: true
}, {
  text: 'Book hotell',
  completed: false
}, {
  text: 'Book taxi to airport',
  completed: true
}]

const filters = {
  searchText: ''
}

const renderTodos = function (todos, filters) {

  //use filter method for the title search string and save it to filters variable
    const filteredTodos = todos.filter(function (todo) {
        return todo.text.toLowerCase().includes(filters.searchText.toLowerCase())
    })

    const notDone = filteredTodos.filter(function (todo) {
      return !todo.completed
    })

    //Empty the div containg the result, this has to be between filter and the display of the result
    document.querySelector('#todos').innerHTML = ''

    const summary = document.createElement('h4')
    summary.textContent = `You found ${notDone.length} hits on this search that are not complete`
    document.querySelector('#todos').appendChild(summary)



    //loop through note object, create a p tag for the title searched and append to the div
    filteredTodos.forEach(function (todo) {
        const noteEl = document.createElement('p')
        noteEl.textContent = todo.text
        document.querySelector('#todos').appendChild(noteEl)

    })
    elem = document.createElement("hr")
    document.querySelector('#todos').appendChild(elem)
}

document.querySelector('#search-todo').addEventListener('input', function (e) {
  filters.searchText = e.target.value
  renderTodos(todos, filters)
})

所以搜索的结果,如果在我附加到我的#todos div 的 p 标签中也有 !todo.completed,那么只有那些 p 标签应该具有黄色的 p 背景颜色。

谢谢

【问题讨论】:

  • 是的,这应该是可能的 - 但究竟是什么不适合给定的代码?
  • 我对js很陌生,代码运行良好,但我想学习如何更改状态为false的p标签的背景颜色(未完成的任务)在进行字符串过滤时。所以只有没有完成的p标签才会得到黄色的背景色

标签: javascript html css arrays object


【解决方案1】:

只需在 forEach 循环中添加此 if 语句:

if (!todo.completed) {
    noteEl.style.backgroundColor = "yellow";
}

完整的循环应该是这样的:

filteredTodos.forEach(function (todo) {
    const noteEl = document.createElement('p');
    noteEl.textContent = todo.text;
    if (!todo.completed) {
        noteEl.style.backgroundColor = "yellow";
    }
    document.querySelector('#todos').appendChild(noteEl);
})

【讨论】:

  • 没问题@user2371684
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-24
  • 1970-01-01
  • 1970-01-01
  • 2016-06-02
  • 2019-06-20
  • 2014-03-15
相关资源
最近更新 更多