如果 JavaScript 返回 true,则重定向到 href


Redirect to href if javascript return true

>我有一个<a>链接和一个复选框,我想仅在javascript返回true时才重定向到href(选中该框)

这是我的代码:

我的脚本文件:

function fb_checkbox() {
    if (document.getElementById("checkAGB").checked == false) {
        document.getElementById('notAccepted').style.display = "block";
        return false;
    }else{
        return true;
    }

在我的 PHP 文件中:

<a href="'.$loginUrl.'" onclick="fb_checkbox();">Sign in with Facebook</a>

尝试在javascript中使用它:

function fb_checkbox(url) { ... else{ window.location.href = url; }

在PHP方面:

<a href="'.$loginUrl.'" onclick="fb_checkbox(this.href);return false;">Sign in with Facebook</a>

它应该有效。

您需要

onclick属性的值中添加return

试试这个:

<a href="'.$loginUrl.'" onclick="return fb_checkbox();">Sign in with Facebook</a>

下面是工作示例:

function fb_checkbox() {
    if (document.getElementById("checkAGB").checked == false) {
        document.getElementById('notAccepted').style.display = "block";
        return false;
    }else{
        return true;
    }
  }
<input type="checkbox" id="checkAGB"/>
<div id="notAccepted" style="display:none">Check the checkbox!</div>
<a href="http://google.com" onclick="return fb_checkbox();">Works</a>

尝试如下:

<a href="javascript:void()" onclick="fb_checkbox();">Sign in with Facebook</a>
function fb_checkbox() {
    if (document.getElementById("checkAGB").checked == false) {
        document.getElementById('notAccepted').style.display = "block";
        return false;
    }else{
        window.location.href="<?=$loginUrl?>";
    }