Uncaught TypeError: невозможно получить доступ к свойству "id", цель не определена - PullRequest
0 голосов
/ 13 июля 2020
• 1000 Учебник Ларри Уллмана о 'Modern Javascript' , но я боюсь, что учебник, которому я следую, устарел и поэтому не работает слишком хорошо в новое время.

Ошибка Я получаю с Firefox Developer Edition :
Uncaught TypeError: can't access property "id", target is undefined
    setThemeCookie http://127.0.0.1:5500/js/index.js:52
    onload http://127.0.0.1:5500/js/index.js:68

А вот мой код:

Index. js:

function setTheme(theme) {  
  var css = null;
  if (document.getElementById('cssTheme')) {
    css = document.getElementById('cssTheme');
    css.href = 'css/' + theme + '.css';
  }else{
    css = document.createElement('link');
    css.rel = 'stylesheet';
    css.href = 'css/' + theme + '.css';
    css.id = 'cssTheme';
    document.head.appendChild(css);
  }
};

// make cookie when themeButton clicked
function setThemeCookie(e) {
  if (typeof e == 'undefined') e = window.event;

  if (e.preventDefault) {
    e.preventDefault();
  } else {
    e.returnValue = false;
  }

  var target = e.target || e.srcElement;

  // bake cookie
  var expire = new Date();
  expire.setDate(expire.getDate() + 7);
  COOKIE.setCookie('theme', target.id, expire);

  // update cookie recipe
  setTheme(target.id);
  return false;
}

// Use saved theme on window load:
window.onload = function () {
  document.getElementById('darkTheme').onclick = setThemeCookie;
  document.getElementById('lightTheme').onclick = setThemeCookie;
  document.getElementById('sdarkTheme').onclick = setThemeCookie;
  document.getElementById('slightTheme').onclick = setThemeCookie;

  var theme = COOKIE.getCookie('theme');
  if (theme) {
    setThemeCookie(theme);
  }
};

соответствующие части index. html:

<!--head-->
<link rel="stylesheet" href="css/style.css">
<link rel="stylesheet" href="css/darkTheme.css" id="cssTheme">
<script defer src="js/index.js"></script>
<script defer src="js/cookie.js"></script>

<!--body-->
<abbr title="dark"><button id="darkTheme"></button></abbr>
<abbr title="light"><button id="lightTheme"></button></abbr>
<abbr title="solarized dark"><button id="sdarkTheme"></button></abbr>
<abbr title="solarized light"><button id="slightTheme"></button></abbr>

darkTheme. css как визуализация того, как выглядит файл theme. css:

:root{
  --text-1: #ddd;
  --text-2: #aaa;
  --text-3: #777;
  --bg-0: #101010;
  --bg-1: #111;
  --bg-2: #181818;
  --bg-3: #202020;
}
#footer-logo{
  filter: hue-rotate(0deg);
}

Я подозреваю, что проблема с target.id никогда не указывается, и даже если бы был e.id или css .id, он не смог бы получить значение .id из target.id ( если в этом есть смысл). Я также новичок в языке JavaScript, поэтому могу не понимать очевидного. Спасибо.

1 Ответ

0 голосов
/ 14 июля 2020

Вы можете попробовать это

const div1 = document.getElementById('div1');
const align = div1.getAttribute('align');

alert(align); // Shows the value of align for the element with id="div1"

Источник: https://developer.mozilla.org/en-US/docs/Web/API/Element/getAttribute

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...