У меня есть массив, который я хотел бы отображать при загрузке страницы. В моем коде ниже он срабатывает в блоке кода, когда я нажимаю новый элемент массива.
Есть ли способ взять часть кода, в котором я перебираю массив и помещаю его в функцию, и вызываю эту функцию при загрузке страницы, а затем вызываю ее всякий раз, когда я нажимаю новый элемент массива.
Это HTML-код:
<h1>Todos</h1>
<form action = "" id = "addTodo">
<input type = "text" name = "inputTodo" placeholder = "Insert new todo">
<button>Add Todo</button>
</form>
<input id = "search-todo" type = "text" placeholder = "Search todo">
<button id = "reset-search" type = "reset" value = "reset" onclick = "window.location.reload()">New search</button>
<div id = "todos"></div>
<script src = "js/index.js"></script>
и это мой код js:
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
}]
//Insert new todo
document.querySelector('#addTodo').addEventListener('submit', function (e) {
e.preventDefault()
newTodo = document.querySelector('[name = "inputTodo"]').value;
todos.push({text: newTodo, completed: false});
console.info(todos)
//show the whole array
todos.forEach(function (todo,) {
const p = document.createElement('p')
p.textContent = todo.text
document.querySelector('body').appendChild(p)
let radio_button_true = document.createElement("INPUT") // Creating input tag for true button
radio_button_true.setAttribute("type", "radio")
let radio_button_false = document.createElement("INPUT") // Creating input tag for false button
radio_button_false.setAttribute("type", "radio")
//create variable to generate random id for radiobutton
const id = Math.random().toString(36)
radio_button_true.setAttribute("name", id)
radio_button_false.setAttribute("name", id)
//Switch loop over the completed
switch (todo.completed) {
case true:
radio_button_true.setAttribute("checked", "true") // Mark true button as checked
break
case false:
radio_button_false.setAttribute("checked", "true") // Mark false button as checked
break
default:
break
}
document.body.appendChild(radio_button_true) // Appending true radio button to body
let radio_button_true_node = document.createElement("span")
let radio_button_true_text = document.createTextNode("true") // Creating span text with true
radio_button_true_node.appendChild(radio_button_true_text)
document.body.appendChild(radio_button_true_node)
document.body.appendChild(radio_button_false) // Appending false radio button to body
let radio_button_false_node = document.createElement("span")
let radio_button_false_text = document.createTextNode("false") // Creating span text with false
radio_button_false_node.appendChild(radio_button_false_text)
document.body.appendChild(radio_button_false_node)
})
const notDone = todos.filter(function (todo) {
return !todo.completed
})
const summary = document.createElement('h2')
summary.textContent = `You have a total of ${notDone.length} todos pending`
document.querySelector('#addTodo').appendChild(summary)
})
//contains the search text
const filters = {
searchText: ''
}
//Function that takes in the notes object and the search text as parameters
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} hit${notDone.length !== 1 ? 's' : ''} on this search that is 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;
if (!todo.completed) {
noteEl.style.backgroundColor = "yellow";
}
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)
})
Благодарность :)



![Безумие обратных вызовов в javascript [JS]](https://i.imgur.com/WsjO6zJb.png)


Приведенный ниже код запускает функцию сразу после загрузки страницы. Вы можете поместить в него свою функцию массива.
window.onload = function() {
the_function_you_need_to_call(param1, param2);
};
для части II-
condition_after_which_you_push_data_in_array
{
array.push();
the_function_you_need_to_call(param1, param2);
}
Было бы полезно небольшое пояснение ... Например, какова цель
array.push()без параметров?