2011-07-23 36 views
2

我有一個1或0的變量,如果它是1,那麼頁面應該轉到cnn.com,如果它是0,它應該去google.com。問題是,當它是1或0時,它總是會轉到google.com。看看在http://jsbin.com/ucovef/7由於運行的版本提前如果語句不執行第二個參數,則使用Javascript

function random(){ 
var randomnumber=Math.floor(Math.random()*2) 
document.getElementById('randomnumber').innerHTML=(randomnumber); 
check_random() 
} 
function check_random(){ 
if (randomnumber = 0){ 
this.location.href ="http://www.cnn.com"; 
} 
if (randomnumber = 1){ 
this.location.href="http://www.google.com"; 
} 
} 

回答

4

您需要:

if (randomnumber == 0) 

和:

if (randomnumber == 1) 

表達randomnumber = 0randomnumber = 1賦值表達式該編號分配給0和對v的1儘管他們在一個if有條件的陳述中。

因此,它總是轉到google.com因爲一切不等於0的JavaScript一個true表達。

2

你必須用==來檢查。 =設置值而不是評估它。我也建議將隨機數傳遞給函數。

function random(){ 
    var randomnumber=Math.floor(Math.random()*2) 
    document.getElementById('random').innerHTML=(randomnumber); 
    check_random(randomnumber) 
} 

function check_random(randomnumber){ 
    if (randomnumber == 0){ 
     this.location.href ="http://www.cnn.com"; 
    } 
    else if(randomnumber == 1){ 
     this.location.href="http://www.google.com"; 
    } 
} 
+0

謝謝,但仍然不能正常工作http://jsbin.com/ucovef/11 –

+0

不要使用相同的名稱作爲變量使用的ID。將div的id重命名爲「random」並將隨機數傳遞給腳本,就像我上面描述的那樣。它工作得很好。 http://jsbin.com/ucovef/18 – Dan

1

您必須使用==不等於!!!!!!!!!!!!!!!!

0

本,你使用random的局部變量check_random。這不起作用。試試這個

function random(){ 
var randomnumber=Math.floor(Math.random()*2) 
document.getElementById('randomnumber').innerHTML=(randomnumber); 
check_random(randomnumber) 
} 
function check_random(n){ 
if (n == 0){ 
this.location.href ="http://www.cnn.com"; 
} 
if (n == 1){ 
this.location.href="http://www.google.com"; 
} 
} 
相關問題