我想在我的网页上创建一个按钮,单击该按钮时会设置一个具有指定值的 cookie。 cookie 应该对整个域、其所有目录和子域有效。
我现在使用的代码是这样的:
function setCookie(cname, cvalue, exdays)
{
var d = new Date();
d.setTime(d.getTime() + (365*24*60*60*1000));
var expires = "expires="+ d.toUTCString();
document.cookie = cname + "name1" + cvalue + "value1" + expires + ";path=/";
}
然后,一旦设置了 cookie 及其值,我希望该按钮从页面中删除。另外,下次加载页面时,我想检查 cookie 和值是否存在,如果不存在,则显示按钮,否则删除按钮。
上下文中的按钮有一个 id:删除
我使用此代码来检查 cookie 及其值:
function getCookie(name1)
{
var name = name1 + "value1";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.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 "";
}
我从这里找到了这些代码:https://www.w3schools.com/js/js_cookies.asp
如果 cookie 及其值存在,我将使用此代码删除该元素:
function removeElement(elementId)
{
var element = document.getElementById(delete);
element.parentNode.removeChild(element);
}
我从这里获取了此代码:https://www.abeautifulsite.net/adding-and-removing-elements-on-the-fly-using-javascript
我不知道如何链接这两个功能来执行所需的操作。
最佳答案
这是适合您的可行解决方案。查看代码中的注释。
你是 JS 新手吗?在这种情况下,您应该看看 codecademy 。它是免费的,您将很快学会基础知识。
Note that SO does not allow you to check or set cookies. For that reason the runable code below will cause an error. Here is a working fiddle.
if (getCookie('myCookie')) removeElement('myButton'); // remove if cookie is set
if (document.getElementById('myButton')) document.getElementById('myButton').onclick = function() { // bind function to clickevent
setCookie('myCookie', 'myValue', 1); // set cookie
removeElement('myButton'); // remove button
}
function setCookie(cname, cvalue, exdays) { // your setCookie Funktion
var d = new Date();
d.setTime(d.getTime() + (365 * 24 * 60 * 60 * 1000));
var expires = "expires=" + d.toUTCString();
document.cookie = cname + '=' + cvalue + '; '+ expires + ";path=/"; // reset to w3schools solution
}
function getCookie(name) { // your getCookie Funktion
// removed 'var name = ...' because you wont find your cookie if you changing the name here
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.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 removeElement(elementId) { // your removeElement Function
var element = document.getElementById(elementId); // variable delete was undefined, if your buttons id was delete you had to write it in ''
element.parentNode.removeChild(element);
}
<button type="button" id="myButton">
click me
</button>
关于javascript - 如何根据cookie值从页面中删除元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56259119/