简体   繁体   English

如何根据Cookie值从页面中删除元素?

[英]How do delete elements from page based on cookie value?

I want to create a button on my webpage, which when clicked, sets a cookie with a specified value. 我想在我的网页上创建一个按钮,单击该按钮可将cookie设置为指定值。 The cookie should be valid for the entire domain, all its directories and sub-domains. Cookie对于整个域,其所有目录和子域均应有效。

The code I'm using now is this: 我现在使用的代码是这样的:

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=/";
    }

Then, once the cookie and its value is set, I want that button to get deleted from the page. 然后,一旦设置了cookie及其值,我希望该按钮从页面中删除。 Also, next time the page loads, I want to check if the cookie and the value exists and if not, show the button or else, delete the button. 另外,下一次页面加载时,我要检查cookie和值是否存在,如果不存在,请显示按钮,否则请删除按钮。

The button in context has an id: delete 上下文中的按钮具有一个ID:删除

I'm using this code to check for cookie and its value: 我正在使用此代码来检查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 "";
    }

I've found these codes from here: https://www.w3schools.com/js/js_cookies.asp 我从这里找到了这些代码: https : //www.w3schools.com/js/js_cookies.asp

I'm going to use this code to delete the element if the cookie and its value is present: 如果存在cookie及其值,我将使用此代码删除元素:

function removeElement(elementId)
    {
        var element = document.getElementById(delete);
        element.parentNode.removeChild(element);
    }

I've taken this code from here: https://www.abeautifulsite.net/adding-and-removing-elements-on-the-fly-using-javascript 我从这里获取了以下代码: https : //www.abeautifulsite.net/adding-and-removing-elements-on-the-fly-using-javascript

I don't know how to link those 2 fuctions to carry out the required action. 我不知道如何链接这两个功能以执行所需的操作。

Here is a working solution for you. 这是为您提供的可行解决方案。 Take a look at the comments inside the Code. 看一下代码中的注释。

Are u new to JS? 您是JS新手吗? in this case you should take a look at codecademy . 在这种情况下,您应该看看codecademy Its for free and you will learn the basics very fast. 它是免费的,您将很快学习基础知识。

Note that SO does not allow you to check or set cookies. 请注意,SO不允许您检查或设置Cookie。 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> 

Going by your requirements you just want to delete a specific button if the cookie is present. 根据您的要求,如果存在cookie,您只想删除一个特定的按钮。 In this case you will need to do 2 things. 在这种情况下,您将需要做两件事。

  1. Call the getCookie and based on the return value call the removeElement at the end of the setCookie method. 调用getCookie并基于return值在setCookie方法末尾调用removeElement

    Note: I am assuming your setCookie method is synchronous . 注:我假设你setCookie的方法是synchronous

  2. Load the button by default and do the same as Step 1 once the page is loaded . 默认情况下,加载button ,页面loaded ,请与步骤1相同。

To summarize, your mrthods should look like this: 总而言之,您的方法应如下所示:

setCookie method: setCookie方法:

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=/";
    if(getCookie(cname)) removeElement('delete');
}

After Loading the document: 加载文档后:

document.onload = ()=>{
    if(getCookie(cname)) removeElement('delete');
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM