Человек написал программу (макет для более сложного варианта), только неудобно, что файлы настроек нужно загружать каждый раз из интерфейса. Поправьте пожалуйста код, чтобы автоматически подгружалось.
index.html
Код:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Рецепты</title>
<style>
hr {
border: none;
background-color: black;
color: black;
height: 2px;
}
</style>
</head>
<body>
<div id="recipe-container">
<strong>Рецепты</strong>
<input type="file" id="recipe-selector">
<p id="recipe-error-check"></p>
</div>
<div>
<strong>Ингредиенты</strong>
<input type="file" id="ingredient-selector">
<p id="ingredient-error-check"></p>
</div>
<div id="input-container"></div>
<button id="submit">Обработать</button>
<button id="clear">Очистить</button>
<button id="check-all">Выбрать всё</button>
<p id="answer"></p>
<script src="main.js"></script>
</body>
</html>
main.js
Код:
// функция переводит русские слова на латиницу это нужно для создания уникальных id для checkbox-ов
function rus_to_latin ( str ) {
var ru = {
'а': 'a', 'б': 'b', 'в': 'v', 'г': 'g', 'д': 'd',
'е': 'e', 'ё': 'e', 'ж': 'j', 'з': 'z', 'и': 'i',
'к': 'k', 'л': 'l', 'м': 'm', 'н': 'n', 'о': 'o',
'п': 'p', 'р': 'r', 'с': 's', 'т': 't', 'у': 'u',
'ф': 'f', 'х': 'h', 'ц': 'c', 'ч': 'ch', 'ш': 'sh',
'щ': 'shch', 'ы': 'y', 'э': 'e', 'ю': 'u', 'я': 'ya',
'ъ': 'ie', 'ь': '', 'й': 'i'
}, n_str = [];
for ( var i = 0; i < str.length; ++i ) {
n_str.push(
ru[ str[i] ]
|| ru[ str[i].toLowerCase() ] == undefined && str[i]
|| ru[ str[i].toLowerCase() ].replace(/^(.)/, function ( match ) { return match.toUpperCase() })
);
}
return n_str.join('');
}
// селектор файла с рецептами
const recipesSelector = document.getElementById("recipe-selector");
recipesSelector.addEventListener('change', (event) => {
const fileList = event.target.files;
const file = fileList[0];
const reader = new FileReader();
reader.readAsText(file);
// то что происходит после загрузки файла с рецептами
reader.onload = function() {
let text = reader.result;
const recipes = JSON.parse(text)["recipes"]; // все рецепты из полученного файла
const button = document.querySelector("#submit");
const answer = document.querySelector("#answer");
// кнопка обработки. Не работает, пока не загружен файл
button.addEventListener("click", () => {
// список всех выбранных ингредиентов
const selected = [...document.querySelectorAll("input[id]:checked")].map(
(input) => input.id
);
answer.innerHTML = ""; // очистка ответа
let lines = 0;
//сравнение массива выбранных ингредиентов с массивом всех ингредиентов
let intersectionsList = [];
let intersections;
for (recipe of recipes) {
intersections = recipe.ingredients.filter((item) =>
selected.includes(rus_to_latin(item).toLowerCase()))
recipeIntersections = {"name": recipe.name, "intersections": intersections} // словарь {имя, пересечения}
intersectionsList.push(recipeIntersections); // добавляем словарь в список
}
// сортировка
intersectionsList.sort((a, b) => {
return b.intersections.length-a.intersections.length;
});
// вывод на экран ингредиентов
for (i of intersectionsList) {
if (i.intersections.length !== 0){
let line = document.createElement("hr");
let nextLine = document.createElement("br");
answer.append(i.intersections.join(", ") + ": " + i.name);
answer.append(nextLine);
answer.append(line);
lines++;
}
}
if (lines === 0){
answer.innerHTML = "Таких рецептов нет!";
}
});
}
});
// селектор ингредиентов
const ingredientsSelector = document.getElementById('ingredient-selector');
ingredientsSelector.addEventListener('change', (event) => {
const fileList = event.target.files;
const file = fileList[0];
const reader = new FileReader()
reader.readAsText(file);
// функционал после загрузки файла с ингредиентами
reader.onload = function() {
let text = reader.result
let ingredients = JSON.parse(text)["ingredients"]
let inputContainer = document.getElementById("input-container")
inputContainer.innerHTML = "";
// вывод всех ингредиентов из файла
for(let i = 0; i<ingredients.length; i++) {
let ingredientCheckbox = document.createElement("input")
ingredientCheckbox.id = rus_to_latin(ingredients[i]).toLowerCase();
ingredientCheckbox.type = "checkbox"
let ingredientLabel = document.createElement("label")
ingredientLabel.for = ingredientCheckbox.id
ingredientLabel.id = ingredientCheckbox.id + "-label"
ingredientLabel.innerHTML = ingredients[i] + "\n"
let nextLine = document.createElement("br")
inputContainer.append(ingredientCheckbox);
inputContainer.append(ingredientLabel);
inputContainer.append(nextLine)
}
}
});
// кнопка очистки выбора
let clearButton = document.getElementById("clear")
clearButton.addEventListener("click", () => {
const selected = [...document.querySelectorAll("input[id]:checked")].map(
(input) => input.id
);
for (ingredient of selected) {
const getInput = document.getElementById(ingredient)
getInput.checked = false;
}
});
// кнопка "Выбрать все"
let checkAllButton = document.getElementById("check-all")
checkAllButton.addEventListener("click", () => {
const inputs = [...document.querySelectorAll("input[id]")].map(
(input) => input.id
);
for (ingredient of inputs) {
const getInput = document.getElementById(ingredient)
getInput.checked = true;
}
});
recipes.json
Код:
{
"recipes": [
{
"name": "Пицца",
"ingredients": [
"Мука", "Вода", "Соль", "Колбаса", "Помидоры", "Соус"
]
},
{
"name": "Хлеб",
"ingredients": ["Мука", "Вода", "Соль"]
},
{
"name": "Кекс",
"ingredients": ["Мука", "Вода", "Яйца", "Соль", "Сахар"]
}
]}
ingredients.json
Код:
{
"ingredients": [
"Мука",
"Вода",
"Сахар",
"Яйца",
"Соль",
"Колбаса",
"Помидоры",
"Соус"
]}
Другой человек подсказал такой фрагмент кода, только не знаю, как его интегрировать.
https://developer.mozilla.org/ru/doc...PI/Using_Fetch
Код:
fetch('/recipes.json')
.then((response) => {
return response.json();
})
.then((data) => {
console.log(data);
});