【发布时间】:2015-05-29 17:51:58
【问题描述】:
我需要为一个类调试这段代码,我已经修复了一些问题,但我不确定它为什么不起作用。它应该计算短语中元音的数量并将它们返回到我相信的 div 元素中。但是它总是返回“未定义的元音”
这里是html
<!doctype html>
<html>
<!-- vowels.html -->
<head>
<meta charset="utf-8">
<title>Vowels</title>
<link rel="stylesheet" href="../css/easy.css">
<script src="vowels.js"></script>
</head>
<body>
<header>
<h1>I'd like to buy a vowel</h1>
</header>
<main>
<label>
Type a phrase here:
<input type='text' id='textBox'> </input>
</label>
<button id='countBtn' type='button'> <!--changed countButton to countBtn-->
Count Vowels (a,e,i,o,u)
</button>
<div id='outputDiv'>
</div>
</main>
<footer>
<hr>
<p>© UO CIS 111 2015 April™ LLC</p>
</footer>
</body>
</html>
这是我的 JS
function countVowels() {
var textBox, phrase, i, pLength, letter, vowelCount; //removed alert count vowels
textBox = document.getElementById('textBox'); //corrected spelling of Element
phrase = textBox.value;
phrase = phrase.toLowerCase; //switched to lower case
for(i = 0; i < phrase.length; i+= 1) {
letter = phrase[i];
if (letter == 'a' || letter == 'e' || letter == 'i' || letter == 'o' || letter == 'u') { //fixed the spelling of letter. added another = in letter = 'e'
vowelCount = vowelCount + 1;
}
}
alert(vowelCount + ' vowels');
var outArea = document.getElementById('outputDiv'); //corrected to outputDiv instead of outputId and put document. in front of the getElement
outArea.innerHTML = vowelCount + ' vowels in ' + phrase;
}
function init(){
alert('init vowels');
var countTag = document.getElementById('countBtn'); //switched to semi- colon and condensed to single line
countTag.onclick = countVowels;
}
window.onload = init;
这是JSFiddle
【问题讨论】:
-
你知道如何在 JavaScript 控制台中使用调试器吗?如果你使用它,你会很容易找到答案。逐行遍历
countVowels()代码并查看vowelCount变量的值。是你所期望的吗? -
如果您不知道如何使用 JavaScript 调试器,很容易找到。例如,如果您使用 Chrome,这里有一些关于 Chrome DevTools 的信息。在那里寻找调试器部分并尝试一下。
-
这是一个不错的 JSFiddle:jsfiddle.net/acjy656v
-
您必须致电
toLowerCase,如toLowerCase()。
标签: javascript html debugging