2016-12-22 7 views
2

Я новичок в JS, и я пытаюсь сделать очень простую программу, которая будет принимать входные данные и создавать соответствующий вывод. Тем не менее, я делаю что-то неправильно, потому что он не работает. Вот мой код.Трудности с document.getElementById(). Значение

<html> 
<head> 
    <title>Test</title> 
    <h1>Test</h1> 
</head> 
<body> 
    <p>Please type your input into the box below.</p> 
    <input type="number"; id="input"> 
    <button type="submit"; onclick="Output()">Submit</button> 
    <pre id="OutputHere">Type an input first!</pre> 
    <script type="text/javascript"> 
     window.onload = function { 
      if(document.getElementById("input").boolValue != null); { 
       Output(); 
      } 
     } 
     function Output() { 
      var input = document.getElementById("input").value 
      switch(input) { 
       case 1: 
        document.getElementById("OutputHere").value="4" 
       case 2: 
        document.getElementById("OutputHere").value="9" 

      } 
     } 

ответ

1

Я согласен с проблемами, которые другие ответы указывали. Я также предложил бы использовать addEventListener в вашем JavaScript вместо установки тега onclick в вашем HTML.

Если это помогает, я немного изменил код.

var button = document.getElementById('submit'); 
 
var input = document.getElementById('input'); 
 

 
button.addEventListener("click", Output); 
 

 
function Output() { 
 
    var value = document.getElementById("input").value; 
 
    var pre = document.getElementById("OutputHere"); 
 

 
    switch(value){ 
 
    case "1": 
 
     pre.innerText = "4"; 
 
     break; 
 
    case "2": 
 
     pre.innerText = "9"; 
 
     break; 
 
    default: 
 
     pre.innerText = "Default text"; 
 
     break; 
 
    } 
 
}
<p>Please type your input into the box below.</p> 
 
<input type="number" id="input"> 
 
<button id="submit">Submit</button> 
 
<pre id="OutputHere">Type an input first!</pre>

+0

Ого, так несправедливо, от Connor части :) Мой ответ был первый, и он работает, разъяснены и все. Без обид spencer.sm – Ionut

+0

@Ionut +1, но не для тех, кто первым, а за качество контента. – zer00ne

+0

@ zer00ne, спасибо. Я рад за признательность. Мне пришлось приложить некоторые усилия, как и вы, в ответ. – Ionut

2

У вас не хватает () из функции OnLoad, изменить window.onload = function { к window.onload = function() {, также не должно быть ; после атрибутов ввода кнопки /, еще одна ошибка является ; после того, если заявление if (document.getElementById("input").boolValue != null); { должно быть if (document.getElementById("input").boolValue != null) {, также есть нет boolVal всего лишь value. Измените case 1, case 2 на case "1", case "2", так как вводными значениями являются строки.

Предлагаю вам действительно проверить свои ошибки в консоли, чтобы увидеть эти типы синтаксических ошибок.

Вы также можете использовать addEventListener("click", yourFunction); по сравнению с устаревшим, который не будет использоваться больше onclick.

И finnally, а также изменить .value с innerHTML для вывода:

window.onload = function() { 
 
    if (document.getElementById("input").value != null) { 
 
    Output(); 
 
    } 
 
}; 
 

 
function Output() { 
 
    var input = document.getElementById("input").value; 
 
    switch (input) { 
 
    case "1": 
 
     document.getElementById("OutputHere").innerHTML= "4"; 
 
     break; 
 
    case "2": 
 
     document.getElementById("OutputHere").innerHTML= "9"; 
 
     break; 
 
    } 
 
}
<p>Please type your input into the box below.</p> 
 
<input type="number" id="input"> 
 
<button type="submit" onclick="Output()">Submit</button> 
 
<pre id="OutputHere">Type an input first!</pre>

2

Были так много ошибок, я поместил все исправления в окне CSS. Каждое количество элементов списка соответствует местоположению источника.

SNIPPET

/* 4 */ 
 
function out() { 
 
    var input = document.getElementById("input").value 
 
    var output = document.getElementById('output'); //5 
 

 
    switch (input) { 
 
    case '1': // 6 
 
     output.value = "4"; 
 
     break; // 7 
 
    case '2': // 6 
 
     output.value = "9"; 
 
     break; // 7 
 
    default: // 8 
 
     output.value = 'Enter 1 or 2'; 
 
     break; 
 

 
    } 
 
}
/* 
 
1. Added max and min attributes since you are expecting a very limited range of input. 
 
2. Removed the type='submit' which by default will gather all data from a <form>'s form elements with a name and then post(or get) to a server. Obviously you do not meet the requirements nor do you need it. 
 
3. Changed <pre> to <output>. Not only is this element a semantically sound choice, it also accepts and displays values derived from the .value property and .textContent or .innerHTML (there's more properties that can be used, but those are the 3 major ones). 
 
4. Removed window.onload event. In this case, it doesn't matter since loading is not crucial in such a simple design. Removed the validation because by using an input type='number' letters cannot be entered, and it should be in the function. BTW, I don't think there's a .boolValue property in JS. 
 
5. Store the value of output in a variable to save you from carpal tunnel syndrome. 
 
6. All element data is text even if it's 0 to 9. If you want them to be numbers (which you don't in this case), use Number(), parseInt(), or parseFloat() to convert a text string to number data. Since we haven't converted the strings to numbers we must wrap each value in quotes. 
 
7. In switch() add break; at the end of each case statement. Without break; the input will go on to the next case, resulting in unexpected results. 
 
8. The last case statement should be default:. Here you can enter a function/expression that applies to anything that is not 1 or 2. Using the default: this way functions as a validator/filter. 
 
*/
<!doctype html> 
 
<html> 
 

 
<head> 
 
    <title>Test</title> 
 
    <h1>Test</h1> 
 
</head> 
 

 
<body> 
 
    <p>Please type your input into the box below.</p> 
 
    <!--1--> 
 
    <input type="number" id="input" max='2' min='1'> 
 
    <!--2--> 
 
    <button onclick="out()">Submit</button> 
 
    <!--3--> 
 
    <output id="output"></output> 
 

 
</body> 
 

 
</html>

Смежные вопросы