简单的JavaScript代码无法正常工作

时间:2013-12-17 18:13:11

标签: javascript html html5 dom getelementbyid

我遇到以下代码问题。我试图从我的数组中获取一个随机字符串,以便在单击按钮时显示。

<script>
    var button = document.getElementById("button");
    var div = document.getElementById("box");
    var text = document.getElementById("text");
    var array=[ "thanks for clicking", "keep on clicking", "click one more time", "why do you keep on clicking me?", "stop clicking me!"];
function thing(){
    var y = array[Math.floor((Math.random() * array.length)+1)];
    text.value=y;
}

function what(){
    text.value = "what";    
}
</script>
<body>
<form>
<input type="button" id="button" value="click" onClick="what()" />
</form>
<form>
    <input type="text" id="text" value="hey" />
</form>
</body>

3 个答案:

答案 0 :(得分:1)

您需要将javascript块移动到表单下方。

设置时:

var text = document.getElementById("text");

该元素尚不存在。如果您将脚本块移动到表单下方,那么该元素将在调用javascript之前存在。

答案 1 :(得分:0)

您的声明不起作用 - 而且您也没有调用方法将数组中的随机项放置到位。

这将有效:

<script>
    function thing() {
        var array = ["thanks for clicking", "keep on clicking", "click one more time", "why do you keep on clicking me?", "stop clicking me!"];

        var y = array[Math.floor((Math.random() * array.length) + 1)];
        document.getElementById("text").value = y;
    }

    function what() {
        document.getElementById("text").value = "what";
    }
</script>
<body>
    <form>
        <input type="button" id="button" value="click" onclick="thing()" />
    </form>
    <form>
        <input type="text" id="text" value="hey" />
    </form>
</body>

答案 2 :(得分:0)

我在这里发现了几个问题。

您有两个不必要的表单标记,表单标记需要具有名称和ID。 Atleast name属性必须在那里。

检查以下小提琴

http://jsfiddle.net/ayyadurai/3Ru9T/

  <form name="form1" id="form1">
  <input type="button" id="button" value="click" onClick="what()" />

   <input type="text" id="text" value="hey" />
  </form>




var button = document.getElementById("button");
var div = document.getElementById("box");
var text = document.getElementById("text");
var array=[ "thanks for clicking", "keep on clicking", "click one more time", "why do you keep on clicking me?", "stop clicking me!"];


function thing(){
var y = array[Math.floor((Math.random() * array.length)+1)];
form1.text.value=y;

}

function what(){
form1.text.value = "what"; 
            thing();

}