Я хотел проверить, является ли пользовательский ввод гласным или нет.Но программа, показывающая вывод else каждый раз - PullRequest
0 голосов
/ 19 февраля 2019
<p>Please insert a letter: <br/> 
        <input id="demo" type="text" name="letter" placeholder="Insert a letter">
        <button type="button" onclick="test()">Check it</button> <br>
        <span id="res"></span>
    </p>

<script type="text/javascript">
let vowel = document.getElementById('demo').value;

function test() {
    if (vowel === 'a' || vowel === 'e' || vowel === 'i' || vowel === 'o' || vowel === 'u') {
        document.getElementById('res').innerHTML = 'This is a vowel !'; 
    } else {
        document.getElementById('res').innerHTML = 'This is a consonant !'; 

    }
}

Ответы [ 2 ]

0 голосов
/ 19 февраля 2019

Вы определяете vowel только один раз, за ​​пределами test, поэтому он не обновляется и всегда будет равен "".Я также реорганизовал ваше заявление if, используя String.prototype.includes

function test() {
  let vowel = document.getElementById('demo').value;
  if ("aeiou".includes(vowel)) {
    document.getElementById('res').innerHTML = 'This is a vowel !';
  } else {
    document.getElementById('res').innerHTML = 'This is a consonant !';
  }
}
<p>Please insert a letter: <br/>
  <input id="demo" type="text" name="letter" placeholder="Insert a letter">
  <button type="button" onclick="test()">Check it</button> <br>
  <span id="res"></span>
</p>
0 голосов
/ 19 февраля 2019

Ваша переменная vowel устанавливается вне области действия тестовой функции, поэтому она не обновляется при нажатии кнопки.Вам нужно переместить его в область видимости так:

function test() {
    let vowel = document.getElementById('demo').value;

    if (vowel === 'a' || vowel === 'e' || vowel === 'i' || vowel === 'o' || vowel === 'u') {
        document.getElementById('res').innerHTML = 'This is a vowel !'; 
    } else {
        document.getElementById('res').innerHTML = 'This is a consonant !'; 
    }
}
...