undefined innerHTML(尝试刷新时)

时间:2013-04-01 15:42:54

标签: button undefined innerhtml random-access partial-page-refresh

大家好,我正在尝试制作一个随机的话语生成器,但我不想刷新整个页面以获得一个新的字符串,所以我想也许 innerHTML 可能是我的解决方案不幸的是,当我点击按钮时,它会给我一个“ UNDEFINED ”结果。我不知道该怎么办。提前谢谢。

<span id="generator" style="font-size: 20px; font-weight: bold;">
<script language="javascript" type="text/javascript">

Words1 = new Array("blablabla1","blablabla2")
Words2 = new Array("blablabla3","blablabla4")
var random = document.write('- ' +
Words1[Math.floor((Math.random() * 100000) % Words1.length)] +
' ' +
Words2[Math.floor((Math.random() * 100000) % Words2.length)] +
'.\n' );

function refresh(){ 
    document.getElementById('generator').innerHTML = random;
}
</script>
</span>

<input type='button' onclick='refresh()' value='refresh'/>

1 个答案:

答案 0 :(得分:0)

您正在使用span标记包装javascript代码。应该像这样并将代码放在de函数中:

    <span id="generator" style="font-size: 20px; font-weight: bold;"></span>
    <script language="javascript" type="text/javascript">

    function refresh(){ 
  Words1 = new Array("blablabla1","blablabla2")
    Words2 = new Array("blablabla3","blablabla4")

    var random = document.write('- ' +
    Words1[Math.floor((Math.random() * 100000) % Words1.length)] +' ' + Words2[Math.floor((Math.random() * 100000) % Words2.length)] +'.\n' );
        document.getElementById('generator').innerHTML = random;
    }
    </script>


    <input type='button' onclick='refresh()' value='refresh'/>