doujuyang1764 2012-10-04 20:53
浏览 25
已采纳

简单的Javascript函数 - 2个选项,每个选项都转到不同的URL

I'm trying to figure out how to have a Confirm/Decline box pop up when someone clicks a link. When they click "Ok" it takes them to one place, when they click "Cancel" it takes them to another place. Most of my experience is with PHP but usually I can take other JavaScript functions and make them work... can't seem to figure this one out though.

Here's my script:

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; ?>";
    }   
}

Any help would be greatly appreciated!

EDIT: Okay, changed the code as suggested. Now it is:

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; ?>";
}   
}

And the link used is:

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

I still don't get a confirm box...

  • 写回答

2条回答 默认 最新

  • dongwen3093 2012-10-04 20:57
    关注

    Make it top.location instead of just location

    Also, I would recommend not doing answer == 1 for the comparison.

    confirm returns a boolean value anyway. Just do if (answer) {

    The reason for avoiding answer == 1 is that doing == 1 is a non strict comparison and it will eventually bite you if you are not aware of how JavaScript behaves. answer === true is an acceptable way of doing this too.

    Another important detail is that when you do this:

    answer = confirm("something here");
    

    You are declaring answer as a global variable. This is terrible practice and you should avoid it. Just add var before it to fix it.

    var answer = confirm("whatever");
    

    For more information on javascript comparisons: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/Comparison_Operators

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的