изменить цвет фона р с помощью JavaScript в зависимости от результата - PullRequest
0 голосов
/ 29 декабря 2018

Мне нужно изменить цвет фона результата в теге ap, если результат переменной>> 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)
})

Таким образом, результат поиска, если есть также! Todo.completed в тегах p, которые я добавляю в мой #todos div, только те pтеги должны иметь желтый цвет фона.

спасибо

1 Ответ

0 голосов
/ 30 декабря 2018

Просто добавьте этот оператор if в цикл forEach:

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);
})
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...