<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 !';
}
}
最佳答案
您只能在测试之外定义一次元音,因此它不会更新,并且始终等于“”.我还使用
String.prototype.includes
重构了您的if语句
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>