jQuery设置全站域名Cookie路径问题求助
Hey Dan, let's get that cookie working across your entire domain—your current code has a couple of syntax and formatting issues that are blocking the path from being applied correctly. Let's break down the problems and fix them step by step:
Key Issues in Your Current Code
- Incorrect cookie string format: You're using a comma to separate
expiresandpath, but cookies require semicolons. Also, you never defined an actual cookie name/value pair (right now, you're just setting expires and path without identifying what the cookie is for). - Invalid path syntax:
path:'/'uses object literal syntax, but cookie attributes need to be written aspath=/(no colon, just an equals sign). - Unreliable cookie check: Your
checkCookiefunction looks for "expires" in the cookie string, which could match other cookies on your site. You should check for a specific cookie name instead.
Corrected Code
Here's the fixed version of your script with explanations:
$(document).ready(function(e) { $('#closeButton').click(function() { var $this = $(this); if(!$this.data('clicked')) { // Simplified the empty else clause $('.welcomepop').addClass('hide'); addCookie(10); $this.data('clicked', true); // Mark button to prevent duplicate actions } }); }); function addCookie(exdays) { var d = new Date(); d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000)); var expires = "expires=" + d.toGMTString(); // Define a clear cookie name/value for reliable checking later var cookieValue = "hideWelcomePopup=1"; // Combine all parts with semicolons (standard cookie format) document.cookie = `${cookieValue}; ${expires}; path=/`; } function checkCookie() { // Check for our specific cookie instead of generic "expires" string if(document.cookie.indexOf("hideWelcomePopup=1") === -1) { // Cookie doesn't exist—popup stays visible (default state) // alert("Welcome New User"); } else { // Cookie exists—hide the popup $('.welcomepop').addClass('hide'); } } // Run check when page loads to apply saved preference checkCookie();
What Changed?
- Added a proper cookie identifier: We named the cookie
hideWelcomePopupwith a value of1so we can reliably check for it later, avoiding conflicts with other cookies. - Fixed cookie string formatting: We use semicolons to separate each cookie attribute (name/value, expires, path) as required by the cookie specification.
- Corrected the path attribute:
path=/ensures the cookie is accessible across your entire domain, not just the current page. - Improved cookie validation: Instead of looking for "expires", we check specifically for our
hideWelcomePopup=1cookie, eliminating false positives. - Prevented duplicate clicks: We mark the button as clicked after the first press to avoid running the code multiple times accidentally.
Once you update your script with this version, the cookie will be set for your entire domain, and the popup will stay hidden across all pages after the user closes it.
内容的提问来源于stack exchange,提问作者Dan Bruce
相关产品推荐
相关产品推荐

