/
maxxon
/
web-static-labs
Обзор
Документация
Войти
/
maxxon
/
web-static-labs
Код
Запросы
0
Задачи
Пакеты
0
Релизы
0
Аналитика
Безопасность
main
html/lab5/task4/script.js
153 строки
6 KB
Dasha_10
изменения
19 окт 2025, 18:51
19 окт 2025, 18:51
b6adcb0
Код
Авторство
О чём код?
// ------------- Задача 1: Всплывающее окно подписки ------------- const subscriptionPopup = document.getElementById('subscription-popup'); const subscribeButton = document.getElementById('subscribe-button'); const closeButton = document.getElementById('close-button'); const emailInput = document.getElementById('subscription-email'); const emailError = document.getElementById('email-error'); const subscriptionResult = document.getElementById('subscription-result'); function isValidEmail(email) { const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; return emailRegex.test(email); } function showSubscriptionPopup() { const screenWidth = window.innerWidth; const screenHeight = window.innerHeight; const popupWidth = Math.max(300, screenWidth * 0.5); const popupHeight = Math.max(200, screenHeight * 0.3); const popupContent = document.querySelector('.popup-content'); popupContent.style.width = popupWidth + 'px'; popupContent.style.height = popupHeight + 'px'; subscriptionPopup.style.display = 'block'; } function closeSubscriptionPopup() { subscriptionPopup.style.display = 'none'; } function handleSubscription() { const email = emailInput.value; if (!email) { emailError.textContent = 'Пожалуйста, введите e-mail.'; emailInput.style.borderColor = 'red'; return; } if (!isValidEmail(email)) { emailError.textContent = 'Пожалуйста, введите корректный e-mail.'; emailInput.style.borderColor = 'red'; return; } // Если e-mail валиден emailError.textContent = ''; emailInput.style.borderColor = ''; const popupContent = document.querySelector('.popup-content'); popupContent.innerHTML = `<p>Спасибо за подписку! На Ваш адрес ${email} будет направлено письмо.</p>`; setTimeout(() => { closeSubscriptionPopup(); }, 10000); // Обновляем сообщение на основной странице subscriptionResult.textContent = `Подписка выполнена на ${email}`; } // Обработчики событий для подписки subscribeButton.addEventListener('click', handleSubscription); closeButton.addEventListener('click', closeSubscriptionPopup); document.addEventListener('keydown', (event) => { if (event.key === 'Escape' && subscriptionPopup.style.display === 'block') { closeSubscriptionPopup(); } }); subscriptionPopup.addEventListener('click', (event) => { if (event.target === subscriptionPopup) { closeSubscriptionPopup(); } }); // ------------- Задача 2: Таблица контактов с фильтрацией ------------- const addContactForm = document.getElementById('add-contact-form'); const contactsTableBody = document.querySelector('#contacts tbody'); const filterSurnameInput = document.getElementById('filter-surname'); const filterNameInput = document.getElementById('filter-name'); const filterAgeInput = document.getElementById('filter-age'); const filterPhoneInput = document.getElementById('filter-phone'); const filterButton = document.getElementById('filter-button'); let contacts = []; // Массив для хранения контактов // Функция для добавления контакта в таблицу function addContactToTable(contact) { const row = document.createElement('tr'); row.innerHTML = ` <td>${contact.surname}</td> <td>${contact.name}</td> <td>${contact.age || ''}</td> <td>${contact.phone || ''}</td> `; contactsTableBody.appendChild(row); } // Функция для фильтрации контактов function filterContacts() { const surnameFilter = filterSurnameInput.value.toLowerCase(); const nameFilter = filterNameInput.value.toLowerCase(); const ageFilter = filterAgeInput.value.toLowerCase(); const phoneFilter = filterPhoneInput.value.toLowerCase(); // Очищаем таблицу contactsTableBody.innerHTML = ''; const filteredContacts = contacts.filter(contact => { const surnameMatch = contact.surname.toLowerCase().includes(surnameFilter); const nameMatch = contact.name.toLowerCase().includes(nameFilter); const ageMatch = (contact.age || '').toString().toLowerCase().includes(ageFilter); const phoneMatch = (contact.phone || '').toString().toLowerCase().includes(phoneFilter); return surnameMatch && nameMatch && ageMatch && phoneMatch; }); filteredContacts.forEach(addContactToTable); } // Обработчик отправки формы добавления контакта addContactForm.addEventListener('submit', (event) => { event.preventDefault(); const surname = document.getElementById('surname').value; const name = document.getElementById('name').value; const age = document.getElementById('age').value; const phone = document.getElementById('phone').value; const newContact = { surname, name, age, phone }; contacts.push(newContact); addContactToTable(newContact); // Очищаем форму addContactForm.reset(); }); // Обработчик нажатия кнопки "Фильтр" filterButton.addEventListener('click', filterContacts); // Пример данных (можно убрать или заменить) contacts = [ { surname: "Иванов", name: "Иван", age: 30, phone: "123-456-7890" }, { surname: "Петров", name: "Петр", age: 25, phone: "987-654-3210" }, { surname: "Сидоров", name: "Сидор", age: 40, phone: "555-123-4567" } ]; // Инициализация таблицы при загрузке страницы (если есть данные) contacts.forEach(addContactToTable);