1

所以我构建了随机化脚本来打印从 1 到 20 的随机数。这些都是我的 css 文件中的 css 类。所以这就是我想要做的。

我想让javascript打印出随机header id=""

<!-- This is my js file -->
<script type="text/javascript" src="/assets/quotes.js"></script>

<!-- This is what I want -->
<header id="<script>showClass();</script>">

这是我的 js 代码:

var Classes=new Array()

Classes[0] = "one";
Classes[1] = "two";
Classes[2] = "three";
Classes[3] = "four";
Classes[4] = "five";
Classes[5] = "six";
Classes[6] = "seven";
Classes[7] = "eight";
Classes[8] = "nine";
Classes[9] = "ten";
Classes[10] = "eleven";
Classes[11] = "twelve";
Classes[12] = "thirteen";
Classes[13] = "fourteen";
Classes[14] = "fifteen";
Classes[15] = "sixteen";
Classes[16] = "seventeen";
Classes[17] = "eighteen";
Classes[18] = "nineteen";
Classes[19] = "twenty";
Classes[20] = "green";


var Q = Classes.length;
var whichClass=Math.round(Math.random()*(Q-1));
function showClass(){document.write(Classes[whichClass]);}
var random =document.getElementById('random').innerHTML="showClass()";

我怎样才能使javascript呈现在id=""

4

1 回答 1

4

JS 不会在引号中呈现,因为这只是一个字符串。相反,请执行以下操作:

<script type="text/javascript">
   document.write("<header id=\"");
   showClass();
   document.write("\">");
</script>

就个人而言,我更喜欢按照 roXon 的建议在 onLoad 处理程序中添加元素,但我认为上面的内容应该适合你所拥有的。

编辑以匹配问题修订。

于 2013-01-14T05:02:41.543 回答