Почему не работает скрипт?
есть такой скрипт
<!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <style> body { margin: 0; padding: 0; } #holiday { display: none; background: hsl(0,0%,90%); color: hsl(340,100%,50%); font: bold 24px/20px serif; text-align: center; padding: 15px 20px; border: 1px solid hsl(0,0%,50%); border-radius: 12px/9px; } </style> </head> <body> <div id="header"> <div id="logo"></div> <div id="block_time-data"></div> </div> <div id="holiday"> </div> <script type="text/javascript"> var holidays = { '1': { '1': {'start': 0, 'duration': 24, 'compliments': 'С новым годом !'}, '7': {'start': 0, 'duration': 24, 'compliments': 'С рождеством !'} }, '2': { '23': {'start': 0, 'duration': 24, 'compliments': 'С 23 февраля !'} }, '3': { '8': {'start': 0, 'duration': 12, 'compliments': 'С 8 марта !'} }, '4': { '12': {'start': 0, 'duration': 12, 'compliments': 'С днём космонавтики !'} }, '5': { '1': {'start': 0, 'duration': 12, 'compliments': 'С 1 мая !'}, '9': {'start': 0, 'duration': 24, 'compliments': 'С 9 мая !'} }, '6': { '1': {'start': 0, 'duration': 24, 'compliments': 'С 1 июня, Всемирным днём родителей !'} }, '7': { '3': {'start': 0, 'duration': 24, 'compliments': '3 июля, день независимости Республики Беларусь !'} }, '8': { '12': {'start': 0, 'duration': 24, 'compliments': '12 августа международный день молодёжи !'} }, '9': { '1': {'start': 0, 'duration': 24, 'compliments': '1 сентября, день знаний !'} }, '10': { '1': {'start': 0, 'duration': 24, 'compliments': '1 октября, международный день пожилых людей !'} }, '11': { '7': {'start': 0, 'duration': 24, 'compliments': '7 ноября, день октябрьской революции !'} }, '12': { '25': {'start': 0, 'duration': 24, 'compliments': 'С католическим рождеством !'} } }, function catholicDate(year) { var a = year % 19; var b = year % 4; var c = year % 7; var k = Math.floor(year / 100); var p = Math.floor((13 + 8 * k) / 25); var q = Math.floor(k / 4); var m = (15 - p + k - q) % 30; var n = (4 + k - q) % 7; var d = (19 * a + m) % 30; var e = (2 * b + 4 * c + 6 * d + n) % 7; if (d === 29 && e === 6) return new Date(year, 3, 19); if (d === 28 && e === 6 && ((11 * m + 11) % 30 < 19)) return new Date(year, 3, 18); if (d + e > 9) return new Date(year, 3, d + e - 9); else return new Date(year, 2, 22 + d + e); } function orthodoxDate(year) { var a = year % 19; var b = year % 4; var c = year % 7; var d = (19 * a + 15) % 30; var e = (2 * b + 4 * c + 6 * d + 6) % 7; var f = d + e; return f <= 26 ? new Date(year, 3, 4 + f) : new Date(year, 4, f - 26); } function getActualCompliments() { var now = new Date( "2 May 2021 00:00:00:001" ); // кат.пасха "4 April 2021 00:00:00:000", прав.пасха "2 May 2021 00:00:00:000", радуница "11 May 2021 00:00:00:000", троица "20 June 2021 00:00:00:000" var result = fixDates.filter(v => { var currentDate = new Date(now.getFullYear(), v.month - 1, v.day, v.hour); var durms = v.duration * 3600000; console.log(now, currentDate, (now - currentDate) / 3600000); var rg = now - currentDate; return rg <= durms && rg >= 0; }).map(v => v.compliments); var caholic = catholicDate(now.getFullYear()); var ortodox = orthodoxDate(now.getFullYear()); if (caholic.getMonth() == now.getMonth() && caholic.getDate() == now.getDate()) result.push("С католической пасхой!"); if (ortodox.getMonth() == now.getMonth() && ortodox.getDate() == now.getDate()) result.push("С православной пасхой!"); var radunitsa = new Date(ortodox); radunitsa.setDate(radunitsa.getDate() + 9); if (radunitsa.getMonth() == now.getMonth() && radunitsa.getDate() == now.getDate()) result.push("С радуницей !"); var trinity = new Date(ortodox); trinity.setDate(trinity.getDate() + 49); if (trinity.getMonth() == now.getMonth() && trinity.getDate() == now.getDate()) result.push("С троицей!"); return result; } var actualCompliments = getActualCompliments(); console.log(actualCompliments); if (actualCompliments.length > 0) { var hollyday = document.getElementById("hollyday"); hollyday.style.display = "block"; for (var c of actualCompliments) { var div = document.createElement("div"); hollyday.appendChild(div); div.innerHTML = c; } } function foo(month, day, compliment, hour = 0) { return { month: month, day: day, hour: hour, compliment: compliment } } var now9 = new Date(); now9.setDate(now9.getDate() + 9); console.log(now9); var now49 = new Date(); now49.setDate(now49.getDate() + 49); console.log(now49); d = new Date( "2 May 2021 00:00:00:001" ), m; // d = new Date( "9 May 2021 00:00:00:001" ) if((m = holidays[d.getMonth()+1]) && m[d.getDate()]) { m = m[d.getDate()]; if(d.getHours()>=m.start) { var b = document.getElementById("holiday"); if (!b) { b = document.createElement("div"); b.id = "holiday"; document.querySelector("body").appendChild(b); } b.innerHTML = m.compliments; b.style.display = "block"; } } </script> <div id="footer"></div> </body> </html> но почему-то не работает, как исправить? |
Ну научитесь же наконец пользоваться отладчиком, смотреть ошибки в консоле.
|
есть скрипт, работает нормально,
<!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <style> body { margin: 0; padding: 0; } #holiday { display: none; background: hsl(0,0%,90%); color: hsl(340,100%,50%); font: bold 24px/20px serif; text-align: center; padding: 15px 20px; border: 1px solid hsl(0,0%,50%); border-radius: 12px/9px; } </style> </head> <body> <div id="header"> <div id="logo"></div> <div id="block_time-data"></div> </div> <div id="holiday"> </div> <script type="text/javascript"> var holidays = [ { // January Январь '1': {'start': 0, 'duration': 24, 'compliments': 'С новым годом !'}, '7': {'start': 0, 'duration': 24, 'compliments': 'С рождеством !'} }, { // February Февраль '23': {'start': 0, 'duration': 24, 'compliments': 'С 23 февраля !'} }, { // March Март '8': {'start': 0, 'duration': 12, 'compliments': 'С 8 марта !'} }, { // April Апрель '12': {'start': 0, 'duration': 12, 'compliments': 'С днём космонавтики !'} }, { // May Май '1': {'start': 0, 'duration': 12, 'compliments': 'С 1 мая !'}, '9': {'start': 0, 'duration': 24, 'compliments': 'С 9 мая !'} }, { // June Июнь '1': {'start': 0, 'duration': 24, 'compliments': 'С 1 июня, Всемирным днём родителей !'} }, { // July Июль '3': {'start': 0, 'duration': 24, 'compliments': '3 июля, день независимости Республики Беларусь !'} }, { // August Август '12': {'start': 0, 'duration': 24, 'compliments': '12 августа международный день молодёжи !'} }, { // September Сентябрь '1': {'start': 0, 'duration': 24, 'compliments': '1 сентября, день знаний !'} }, { // October Октябрь '1': {'start': 0, 'duration': 24, 'compliments': '1 октября, международный день пожилых людей !'} }, { // November Ноябрь '7': {'start': 0, 'duration': 24, 'compliments': '7 ноября, день октябрьской революции !'} }, { // December Декабрь '25': {'start': 0, 'duration': 24, 'compliments': 'С католическим рождеством !'} } ]; function catholicDate(year) { var a = year % 19; var b = year % 4; var c = year % 7; var k = Math.floor(year / 100); var p = Math.floor((13 + 8 * k) / 25); var q = Math.floor(k / 4); var m = (15 - p + k - q) % 30; var n = (4 + k - q) % 7; var d = (19 * a + m) % 30; var e = (2 * b + 4 * c + 6 * d + n) % 7; if (d === 29 && e === 6) return new Date(year, 3, 19); if (d === 28 && e === 6 && ((11 * m + 11) % 30 < 19)) return new Date(year, 3, 18); if (d + e > 9) return new Date(year, 3, d + e - 9); else return new Date(year, 2, 22 + d + e); } function orthodoxDate(year) { var a = year % 19; var b = year % 4; var c = year % 7; var d = (19 * a + 15) % 30; var e = (2 * b + 4 * c + 6 * d + 6) % 7; var f = d + e; return f <= 26 ? new Date(year, 3, 4 + f) : new Date(year, 4, f - 26); } function getActualCompliments() { var now = new Date(); // кат.пасха "4 April 2021 00:00:00:000", прав.пасха "2 May 2021 00:00:00:000", радуница "11 May 2021 00:00:00:000", троица "20 June 2021 00:00:00:000" var result = holidays.filter(v => { var currentDate = new Date(now.getFullYear(), v.month - 1, v.day, v.hour); var durms = v.duration * 3600000; console.log(now, currentDate, (now - currentDate) / 3600000); var rg = now - currentDate; return rg <= durms && rg >= 0; }).map(v => v.compliments); var caholic = catholicDate(now.getFullYear()); var ortodox = orthodoxDate(now.getFullYear()); if (caholic.getMonth() == now.getMonth() && caholic.getDate() == now.getDate()) result.push("С католической пасхой!"); if (ortodox.getMonth() == now.getMonth() && ortodox.getDate() == now.getDate()) result.push("С православной пасхой!"); var radunitsa = new Date(ortodox); radunitsa.setDate(radunitsa.getDate() + 9); if (radunitsa.getMonth() == now.getMonth() && radunitsa.getDate() == now.getDate()) result.push("С радуницей !"); var trinity = new Date(ortodox); trinity.setDate(trinity.getDate() + 49); if (trinity.getMonth() == now.getMonth() && trinity.getDate() == now.getDate()) result.push("С троицей!"); return result; } var actualCompliments = getActualCompliments(); console.log(actualCompliments); if (actualCompliments.length > 0) { var hollyday = document.getElementById("holiday"); hollyday.style.display = "block"; for (var c of actualCompliments) { var div = document.createElement("div"); hollyday.appendChild(div); div.innerHTML = c; } } function foo(month, day, compliment, hour = 0) { return { month: month, day: day, hour: hour, compliment: compliment } } var now9 = new Date(); now9.setDate(now9.getDate() + 9); console.log(now9); var now49 = new Date(); now49.setDate(now49.getDate() + 49); console.log(now49); d = new Date(); // d = new Date( "9 May 2021 00:00:00:001" ) if((m = holidays[d.getMonth()]) && m[d.getDate()]) { m = m[d.getDate()]; if(d.getHours()>=m.start) { var b = document.getElementById("holiday"); if (!b) { b = document.createElement("div"); b.id = "holiday"; document.querySelector("body").appendChild(b); } b.innerHTML = m.compliments; b.style.display = "block"; } } </script> <div id="footer"></div> </body> </html> но при попытке перенести скрипт в head, перестаёт работать, как это исправить? хочу скрипт вынести в отдельный файл, и подключить к страницам разместил всё в head |
Если перенести скрипт в head, то строки 138-160 начнут выполняться сразу же, до того, как будет загружен весь html документ.
Там есть document.getElementById("holiday"). А html документ еще не загрузился. И нет никакого элемента с id = "holiday" Нужно заключить эту часть в функцию, которая будет вызываться, только когда будет полностью загружен документ по событию DOMContentLoaded https://learn.javascript.ru/onload-ondomcontentloaded |
Цитата:
|
народ, помогите добавить DOMContentLoaded
|
Блондинка,
вам же ссылку дали ... !!! document.addEventListener("DOMContentLoaded", () => { // сюда весь ваш скрипт!!! }); |
возможно ли с помощью https://2ip. ru определить страну пользователя?
|
почему этот скрипт не срабатывает?
<script src="https://api-maps.yandex.ru/2.0/?load=package.full&lang=ru-RU" type="text/javascript"></script> <script type="text/javascript"> ymaps.ready(function(){ var geolocation = ymaps.geolocation; alert(geolocation.country); alert(geolocation.region); alert(geolocation.city); }); </script> как на странице вывести страну пользователя? |
<script src="https://api-maps.yandex.ru/2.0/?load=package.full&lang=ru-RU" type="text/javascript"></script> <script type="text/javascript"> ymaps.ready(function(){ var geolocation = ymaps.geolocation; alert(geolocation.country); alert(geolocation.region); alert(geolocation.city); }); </script> Работает Его надо в теги [ HTML run ]...[ /HTML ] вставлять, а не [ JS ] |
Часовой пояс GMT +3, время: 06:06. |