来自Javascript Array的innerHTML

时间:2012-05-05 20:08:04

标签: javascript html arrays

我试图从数组中保留Javascript上下文。有没有办法让这项工作?还是更优雅的方式?

实施例

<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>

2 个答案:

答案 0 :(得分: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>放在<{>> <{1}}元素的某处。目前,脚本在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." qty时,您还可以处理单数/复数语法值。

1

答案 1 :(得分:1)

我假设您要使用变量i来创建字符串,而不仅仅是字母i。当您在字符串周围使用引号时,该变量不是字符串的一部分。

而不是:

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

只需使用:

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

或:

"There are " + i + " dogs in the yard."
相关问题