显示和删除Javascript中的多个Cookie

时间:2018-08-05 10:07:48

标签: javascript cookies

我想使用javascript cookie在网站上显示最后三个搜索值。我存储最后三个值,但是当我在视图中显示时,它会同时显示所有内容。我有两个问题。

  1. 我想在href内分别显示值。因此用户可以单击并再次搜索。

实际输出

<a href="abc.com?location=1=Dubai; 2=India; 3=SriLanka">1=Dubai; 2=India; 3=SriLanka <span class='rmvcookie'>x</span></a>

期望输出

<a href='abc.com?location=Dubai'>Dubai</a><span class='rmvcookie'>x</span>
<a href='abc.com?location=India'>India</a><span class='rmvcookie'>x</span>
<a href='abc.com?location=SriLanka'>SriLanka</a><span class='rmvcookie'>x</span>
  1. 我创建了removeCookies函数,但它立即删除了所有cookie。我想单独删除Cookie。

此网站也是如此。 makemytrip.ae/holidays-india按任何目的地搜索。它存储值,您可以单独删除它。 我尝试了最后两天,但没有获得正确的代码。谁能帮我?拜托。

JavaScript

var num = 1;

function addCookie() {
  var searchvalue = document.getElementsByClassName("cookiename")[0].value;
  document.cookie = num + "=" + searchvalue;

  if (num >= 3) { //Limit for last three search value
    num = 1;
  } else {
    num++;
  }

  var result = document.cookie;
  document.getElementById("list").innerHTML = "<a href='abc.com?location=" + result + "'>" + result + "</a> <span class='rmvcookie' onclick='removeCookies()'>x</span>";
}

function listCookies() {
  var result = document.cookie;
  document.getElementById("list").innerHTML = "<a href='abc.com?location=" + result + "'>" + result + "</a> <span class='rmvcookie' onclick='removeCookies()'>x</span>";
}

window.onload = function() {
  listCookies();
};

function removeCookies() {
  var res = document.cookie;
  var multiple = res.split(";");
  for (var i = 0; i < multiple.length; i++) {
    var key = multiple[i].split("=");
    document.cookie = key[0] + "=; expires=Thu, 28 May 2030 00:00:00 UTC";
  }
}

HTML

<input type="text" id="searchTxt" class="cookiename" name="asd">
<button onclick='addCookie()'>ADD</button><br>
<button onclick='removeCookies()'>REMOVE</button>
<h1>Cookies List</h1>
<p id="list"></p>

查看 enter image description here

1 个答案:

答案 0 :(得分:0)

我在codepen上写了一个解决方案-https://codepen.io/darius9171/pen/JBBRaz

Stackoverflow不允许您处理带有cookie的代码段,但要求您在指定指向代码笔的链接时编写代码。所以不要关注代码段:D

//set cookies
const cookies = ['Dubai', 'India', 'SriLanka'];
cookies.forEach((name, i) => document.cookie = `${i+1}=${name};`);

//render
const list = document.querySelector('.list');
document.cookie.split('; ').forEach(cookie => {
  const pair = cookie.split('=');
  
  list.innerHTML += `<div class="cookie" data-name="${pair[0]}">${pair[1]} <span class='rmvcookie'>x</span></div>`
})

document.querySelectorAll('.rmvcookie').forEach(span => {
  span.addEventListener('click', (event) => {
    const parent = event.currentTarget.parentNode;
    document.cookie = `${parent.dataset.name}=; expires=Thu, 01 Jan 1970 00:00:01 GMT;`;
    parent.parentNode.removeChild(parent);
  })
})
span {
  color: blue;
  cursor: pointer;
}
<div class="list">
</div>