0

我试图弄清楚当有人单击链接时如何弹出确认/拒绝框。当他们单击“确定”时,会将他们带到一个地方,当他们单击“取消”时,会将他们带到另一个地方。我的大部分经验是使用 PHP,但通常我可以采用其他 JavaScript 函数并使它们工作......不过似乎无法弄清楚这一点。

这是我的脚本:

function confirmChoice(name, newid){
    answer = confirm("Transfer Ownership of this task to " + name + 
                     "? Press Cancel to decline.")
    if (answer == 1) {
        location = "transfer.php?task=<? echo $taskid; ?>&from=<? echo ownerid; ?>&to=" + newid;
    } elseif (answer==0) {
        location = "decline.php?task=<? echo $taskid; ?>";
    }   
}

任何帮助将不胜感激!

编辑:好的,按照建议更改了代码。现在它是:

function confirmChoice(name, newid){
var answer = confirm("Transfer Ownership of this task to " + name + "? Press Cancel to decline.")
if (answer){
location = "transfer.php?task=<? echo $thistaskid; ?>&from=<? echo $ownerid; ?>&to=" + newid;
}else{
location="decline.php?task=<? echo $thistaskid; ?>";
}   
}

使用的链接是:

<a href="#" onclick="confirmChoice(<? echo $requestorname; ?>, <? echo $newid; ?>); return false;"><? echo $requestorname; ?> Requested Ownership</a>

我还是没有收到确认框...

4

2 回答 2

1

让它top.location而不是仅仅location

另外,我建议不要进行answer == 1比较。

confirm无论如何返回一个布尔值。做就是了if (answer) {

避免这样做的原因answer == 1是,doing== 1是一种非严格的比较,如果你不知道 JavaScript 的行为方式,它最终会咬你一口。answer === true也是一种可接受的方式。

另一个重要的细节是,当你这样做时:

answer = confirm("something here");

您将 answer 声明为全局变量。这是一种可怕的做法,你应该避免它。只需var在它之前添加即可修复它。

var answer = confirm("whatever");

有关 javascript 比较的更多信息:https ://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/Comparison_Operators

于 2012-10-04T20:57:24.173 回答
0

如果您使用的是 window.open(),您可以轻松更改目的地的位置,但检查确认返回的内容。

var res = confirm("Do you agree?");

并相应地做你的交通方向

var options = ['http://google.com', 'http://boston.com'];
window.location = options[ res ? 1 : 0 ];
// or
window.open = options[ res ? 1 : 0 ];

小提琴不想玩得很好,但它在我的本地机器上对我有用。
http://jsfiddle.net/kyleouellette/G9KGm/1/

于 2012-10-04T21:26:43.217 回答