[英]change background color of p with javascript depending on result
我需要在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)
})
因此,如果我要附加到我的#todos div的p標簽中也有!todo.completed,則搜索的結果是,只有那些p標簽應具有ap的黃色背景色。
謝謝
只需在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);
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.