2013-12-18 40 views
0

我想讓我的訪問者有5%的機會看到圖像。隨機訪問者看到圖片

<script> 
    var rand = Math.round(Math.rand() * 20) 
    if (rand === 13) { 
     document.write("<img src="http://ima.gs/69/666/314/Placeholder-401x401.png" />") 
    } 
</script> 

當我運行腳本時沒有任何反應。

+0

可能*有*發生,如果沒有其他地方然後在[錯誤控制檯](http://www.netmagazine.com/tutorials/javascript-debugging-beginners)。 – JJJ

回答

6

帶上你的開發工具,在谷歌瀏覽器cmd+shift ictrl+shift i

該隨機方法不叫rand它叫random

var rand = Math.round(Math.random() * 20); 

這是你會在JavaScript控制檯中看到TypeError: Object #<Object> has no method 'rand'

開發工具的錯誤,它們是什麼以及如何使用它們:

編輯: 正如其他人指出的,你的document.write參數也有問題。出現在用"包圍的字符串中的任何"都必須轉義爲不破壞輸出,如下所示\"或者可以使用'代替。

正確轉義字符串

"<img src=\"http://ima.gs/69/666/314/Placeholder-401x401.png\" />" 
"<img src='http://ima.gs/69/666/314/Placeholder-401x401.png' />" 
'<img src="http://ima.gs/69/666/314/Placeholder-401x401.png" />' 
'<img src=\'http://ima.gs/69/666/314/Placeholder-401x401.png\' />' 
+0

@NiettheDarkAbsol糟糕:P –

3

看起來你有太多的雙引號。試試這個:

document.write("<img src='http://ima.gs/69/666/314/Placeholder-401x401.png'/>") 
3

除了使用Math.rand()代替Math.random()有的報價的問題,正如其他人所說,你的代碼可能是一個有點短,更高效。

<script> 
    if(Math.random() < 0.05) { 
     document.write("<img src='http://ima.gs/69/666/314/Placeholder-401x401.png' />"); 
    } 
</script> 

另外,我發現0.05反映5%更清楚地大於 「13 1出20,也就是5%的」 ;-)

+1

你錯過了'Math.rand()'不是一個函數。 – jfriend00

+0

謝謝,修正:-) – Farce

3

要生成一個隨機數,使用Math.random(),不Math.rand()

+1

他們也有報價問題。 – jfriend00