2012-05-05 29 views
1

我想從數組中保留Javascript上下文。有什麼辦法可以做到這一點?或者更優雅的方式?來自Javascript的innerHTML數組

例:

<html> 
<script type="text/javascript"> 

var rand = Math.floor(Math.random() * 6) + 1; 

var i = Math.floor(Math.random() * 6) + 1; 

var arr = ["'There are ' + i + ' dogs in the yard.'","'The other day I saw ' + i + ' pigs that one lake.'","'I can't believe there were ' + i + ' birds in your yard the other day.'","'Why were there ' + i + ' cats in my front yard?'","'There are ' + i + ' rabbits in the yard.'","'There are ' + i + ' snakes in the yard.'"]; 

document.getElementById('fudge').innerHTML = arr[rand]; 
</script> 
<body> 
<div id='fudge'></div> 
</body> 
</html> 
+0

你正在試圖做的是什麼?在這種情況下,「背景」是什麼意思? –

+0

我正在嘗試從數組中獲取JavaScript,並能夠在innerHTML中使用該代碼...或者提醒等等。 – Stephen

回答

2

擺脫了外雙引號的。

var arr = [ 
    'There are ' + i + ' dogs in the yard.', 
    'There are ' + i + ' pigs in the yard.', 
    'There are ' + i + ' birds in the yard.', 
    'There are ' + i + ' cats in the yard.', 
    'There are ' + i + ' rabbits in the yard.', 
    'There are ' + i + ' snakes in the yard.' 
]; 

更新:此外,將您<script>地方下面fudge元素。目前該腳本在fudge存在之前正在運行。


如果你想串與未來的更新的變量,這是行不通的更新。你需要生成一個新的字符串。

您可以改爲創建一個函數。

var animals = ['dogs','pigs','birds','cats','rabbits','snakes']; 

function makeString() { 
    var animal = animals[Math.floor(Math.random() * animals.length)], 
     qty = Math.floor(Math.random() * 6) + 1; 

    return "There are " + qty + " " + animal + " in the yard."; 
} 

makeString(); // "There are 3 dogs in the yard." 

你也可以照顧到單數/複數語法值時qty1

var animals = ['dog','pig','bird','cat','rabbit','snake']; 

function makeString() { 
    var animal = animals[Math.floor(Math.random() * animals.length)], 
     verb = 'is', 
     qty = Math.floor(Math.random() * 6) + 1; 

    if (qty !== 1) { 
     animal += 's'; 
     verb = 'are'; 
    } 

    return "There " + verb + " " + qty + " " + animal + " in the yard."; 
} 

makeString(); // "There is 1 dog in the yard." 
+0

兩件事:你搖滾。我是個白癡。謝謝。 – Stephen

1

我假設你要使用的變量i創建的字符串,而不僅僅是字母i。在字符串周圍使用引號時,該變量不是字符串的一部分。

相反的:

"'There are ' + i + ' dogs in the yard.'" 

只需使用:

'There are ' + i + ' dogs in the yard.' 

或:

"There are " + i + " dogs in the yard."