[英]change background color of p with javascript depending on result
I need to change the background color of a result in ap tag, if the result of a variable is > then 1. I guess this could be accomplished with a if statement maybe? 我需要在ap标签中更改结果的背景色,如果变量的结果>>1。我想这可以通过if语句来完成? This is the code I am working with:
这是我正在使用的代码:
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)
})
So the result of the search, if there are also !todo.completed in the p tags that I am appending to my #todos div, only those p tags should have ap background color of yellow. 因此,如果我要附加到我的#todos div的p标签中也有!todo.completed,则搜索的结果是,只有那些p标签应具有ap的黄色背景色。
thanks 谢谢
Just add this if
statement inside the forEach
loop: 只需在
forEach
循环内添加以下if
语句:
if (!todo.completed) {
noteEl.style.backgroundColor = "yellow";
}
The full loop should look like this: 完整的循环应如下所示:
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);
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.