我在头部使用了这个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,但没有工作......有什么解决方案可以解决这个问题吗?
答案 0 :(得分:1)
您可以按以下方式编写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()">