Создайте массив идентификаторов в cook ie JS - PullRequest
1 голос
/ 29 мая 2020

Я хочу обновить повар ie со своей страницы WP с помощью идентификатора сообщения, которое посещает пользователь. Но моя проблема в том, что каждый раз, когда значение из массива удаляется, а массив всегда содержит только идентификатор, а следующий идентификатор просто переигрывается.

 let post_id = my_script_vars.postID; // this is a variable with some id's
 let arr = [] // i create an array

 function setCookie(name,value,days) {
  var expires = "";
  if (days) {
      var date = new Date();
      date.setTime(date.getTime() + (days*24*60*60*1000));
      expires = "; expires=" + date.toUTCString();
  }
  document.cookie = name + "=" + (value || "")  + expires + "; path=/";

}

index = arr.indexOf(post_id);
if (index == -1) { // if the id is not in the array the push it
  arr.push(post_id);
  } else { // if it is in array then keep all of them
    arr.splice(index, 1);
  }
setCookie("id_film",JSON.stringify(arr),30); 

enter image description here

и я хочу, чтобы в моем массиве хранились все идентификаторы, а не только один.

1 Ответ

1 голос
/ 29 мая 2020

Выполните следующие действия:

  • Не создавайте переменную arr, пока она вам не понадобится
  • Добавьте функцию для чтения ie и верните содержимое как JSON
  • При загрузке страницы прочтите повар ie, обновите свой массив, затем сохраните новое содержимое

Окончательный код должен выглядеть так:

 let post_id = my_script_vars.postID; // this is a variable with some id's

 function setCookie(name,value,days) {
  var expires = "";
  if (days) {
      var date = new Date();
      date.setTime(date.getTime() + (days*24*60*60*1000));
      expires = "; expires=" + date.toUTCString();
  }
  document.cookie = name + "=" + (value || "")  + expires + "; path=/";

}
// Function to read cookie and return as JSON
function getCookie(name) {
    let a = `; ${document.cookie}`.match(`;\\s*${name}=([^;]+)`);
    return a ? JSON.parse(a[1]) : [];
}

// Be sure to execute after DOM is loaded
window.addEventListener('load', function() {
    // Get saved IDs
    let arr = getCookie('id_film');
    index = arr.indexOf(post_id);
    if (index == -1) {
        // if the id is not in the array the push it
        arr.push(post_id);
    }
    setCookie("id_film",JSON.stringify(arr),30);
});
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...