简单的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...

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

If you are using window.open(), you can easily change where that destination is but checking what the confirm returned.

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

and do your traffic direction accordingly

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

The fiddle doesnt want to play nice but it works for me on my local machine.
http://jsfiddle.net/kyleouellette/G9KGm/1/