javascript - Javascript 在单击按钮时多次打开链接
问题描述
我在我的 head 部分使用了这个 javascript,当我点击按钮时,它总是打开目标链接。这里我想打开链接一次
<?php
$onclick = '';
if(!isset($_COOKIE['visited'])) {
setcookie('visited', '1', time()+3600, COOKIEPATH, COOKIE_DOMAIN);
$onclick = 'onclick="window.open(\'https://www.google.com\', \'_blank\')"';
}
?>
用法
<body <?php body_class(); ?> <?php echo $onclick; ?>>
我完美地检查了它的写入cookie但没有工作..有什么解决方案可以解决这个问题吗?
解决方案
可以通过以下方式编写JS代码
/**
* For writing cookie
* @param name {String} name of the cookie
* @param value {*} value of the cookie
* @param days {Number} number of days
*/
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=/";
}
/**
* Get cookie by a name
* @param name {String}
* @returns {*}
*/
function getCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
/**
* Check for already redirected or not. If not then redirect to targeted site.
*/
function redirectToTarget() {
var isAlreadyRedirected = getCookie('redirect');
if (null === isAlreadyRedirected) {
setCookie('redirect', 1, 30); // write for 1 month
window.open('https://www.google.com');
}
}
并从 body onclick 调用 js 函数,如下所示
<body onclick="redirectToTarget()">
推荐阅读
- android - 如何使用 ActivityResultContracts.CreateDocument() 添加意图类型
- python - Pyinstaller:无法在 pyi-makespec 中正确添加二进制文件和数据
- javascript - 如何在 Typescript 中导出和导入类方法?
- powershell - 如何在powershell中将第一个单词更改为黄色而不是白色?
- swift - 检测 USB 连接的问题 - 使用 Swift 代码断开 macOS
- flutter - 请帮助我收到此错误,“状态错误:DocumentSnapshotPlatform 中不存在字段”
- composer-php - 如何找到 composer.phar 文件在哪里
- node.js - 检查用户是否通过 Express.js 和 Firestore 登录
- windows - PeekNamedPipe 意外行为
- wordpress - 显示 Woocommerce 订单自定义字段选择类型