Условия, если Cook ie существует, не работает (Js, Html) - PullRequest
0 голосов
/ 16 апреля 2020

Я сделал закрываемый баннер с Html, CSS и JS. Все работает нормально, но я хочу, чтобы он исчез после того, как пользователь нажал кнопку «Закрыть», и больше никогда его не отобразить (при переходе с сайта на другой или после обновления браузера) я сохранил повар ie, но мой код нужно сделать изменяется, если повар ie не работает

что я делаю не так?

var close = document.getElementsByClassName("close");
var i;

for (i = 0; i < close.length; i++) {
  close[i].addEventListener("click", function() {
    this.parentElement.style.display = 'none';
  });
}

function setCookie(cname, cvalue, exdays) {
  var d = new Date();
  d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
  var expires = "expires=" + d.toUTCString();
  document.cookie = cname + "=" + cvalue + "; " + expires;
}

function getCookie(cname) {
  var name = cname + "=";
  var ca = document.cookie.split(';');
  for (var i = 0; i < ca.length; i++) {
    var c = ca[i];
    while (c.charAt(0) == ' ') c = c.substring(1);
    if (c.indexOf(name) == 0) return c.substring(name.length, c.length);
  }
  return "";
}

function checkCookie() {
  var x = getCookie("clicklink");
  if (x == null) {
    document.getElementById("close").style.display = 'block';
  } else {
    document.getElementById("close").style.display = 'none';

  }
}
.closable {
  margin-top: -1px;
  font-size: 18px;
  color: black;
  position: relative;
  text-align: center;
}

.close {
  cursor: pointer;
  position: absolute;
  top: 15%;
  right: 0%;
  padding: 12px 16px;
  transform: translate(0%, -50%);
}

.close:hover {
  background: #bbb;
}
<div id="close" class="closable" onload="checkCookie()">
  <p><strong>Lorem Ipsum</strong></p>
  <p style="text-align: center">
    s simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.
  </p>
  <span class="close" id="clink" onclick="setCookie('clicklink', 'yes', 7)">
        &times;
  </span>
</div>

Ответы [ 4 ]

2 голосов
/ 16 апреля 2020

Только элемент body имеет атрибут onload (который относится ко всей загрузке документа). div элементы ничего не загружают, поэтому не загружайте. Следовательно, функция checkCookie никогда не вызывается.

A validator выделил бы эту ошибку.

1 голос
/ 16 апреля 2020

Помимо уже упомянутого "Нет загрузки на div", вы не должны писать свой собственный повар ie скрипт

Я бы использовал localStorage вместо куки

Я также делегирую из контейнера

window.addEventListener("load", function() {
  // let divs = localStorage.getItem("divs"); // uncomment on your server
  divs = {"close1": {"closed": true}};        // remove when tested
  // divs = divs ? JSON.parse(divs) : {};      // uncomment on your server
  
  [...document.querySelectorAll("div.closable")].forEach(div => {
    const id = div.id;
    // you could use classList.toggle here instead of style.display
    if (divs[id] && divs[id].closed === true) div.style.display = "none";
  })
  
  document.getElementById("container").addEventListener("click", function(e) { // delegation
    const tgt = e.target;
    if (tgt.classList.contains("close")) {
      const parentDiv = tgt.closest("div.closable"); // find the parent 
      divs[parentDiv.id] = { "closed" : true };
      // localStorage.setItem("divs",JSON.stringify(divs)); // uncomment on server
      parentDiv.style.display = "none";
      console.log(divs)
    }
  })
})
.closable {
  margin-top: -1px;
  font-size: 18px;
  color: black;
  position: relative;
  text-align: center;
}

.close {
  cursor: pointer;
  position: absolute;
  top: 15%;
  right: 0%;
  padding: 12px 16px;
  transform: translate(0%, -50%);
}

.close:hover {
  background: #bbb;
}
<div id="container">
  <div id="close1" class="closable">
    <p><strong>Lorem Ipsum 1</strong></p>
    <p style="text-align: center">
      s simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.
    </p>
    <button class="close">&times;</button>
  </div>
  <div id="close2" class="closable">
    <p><strong>Lorem Ipsum 2</strong></p>
    <p style="text-align: center">
      s simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.
    </p>
    <button class="close">&times;</button>
  </div>
</div>
1 голос
/ 16 апреля 2020

Вы проверяете, если x === null, но ваша функция getCook ie возвращает пустую строку. Поэтому ваше условие никогда не выполняется.

1 голос
/ 16 апреля 2020

если x = "", x==null не вернется true.

Вы должны вернуть null, если нет повара ie.

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