2013-12-17 2 views
-5

다음 코드에 문제가 있습니다. 단추를 클릭 할 때 배열에 임의의 문자열을 표시하려고합니다.쉬운 자바 스크립트 코드가 작동하지 않습니다.

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

은 무엇 코드로 잘못? – showdev

+1

thing()을 호출 할 때 '

' – karthikr

+0

아래로 스크립트를 이동하십시오. –

답변

0

여기 몇 가지 문제점을 발견했습니다.

두 개의 양식 태그가 필요하지 않으며 양식 태그에 이름과 ID가 있어야합니다. 최소한의 이름 속성이 있어야합니다.

다음을 확인 바이올린

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(); 

}

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

당신은 양식 아래에 자바 스크립트 블록을 이동해야합니다.

당신은 설정하는 경우 :

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

요소는 아직 존재하지 않습니다. 스크립트 블록을 양식 아래로 이동하면 javascript가 호출되기 전에 요소가 존재하게됩니다.

+1

많은 문제 중 하나입니다. – canon

관련 문제