[英]I am having a hard time figuring out what is wrong with my html and js file. I need to count the vowels
I need to fix this segment of code for a class and I have fixed a number of things but I'm not sure why it doesn't work. 我需要为一个类修复这段代码,并且已经修复了许多问题,但是我不确定为什么它不起作用。 It is supposed to count the number of vowels in the phrase and return them as an alert.
应该计算出短语中的元音数量,并将其作为警报返回。 When I click on the button nothing appears.
当我点击按钮时,什么也没有出现。
Here's the html. 这是html。 It works fine but added in case I am missing something
它可以正常工作,但在我丢失某些东西的情况下可以添加
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Vowels</title>
<link rel="stylesheet" href="../css/easy.css">
<script src="p3-vowels.js"></script>
</head>
<body>
<header>
<h1>Count Vowels</h1>
</header>
<main>
<label>Type a phrase here:
<input type='text' id='textBox'></input>
</label>
<button id='countBtn' type='button'>
Count Vowels (a,e,i,o,u)</button>
<div id='outputDiv'></div>
</main>
</body>
</html>
here is the JS. 这是JS。 It doesn't seem to register the "on.click" at the end of the code
它似乎没有在代码末尾注册“ on.click”
function countVowels() {
var textBox, phrase, i, pLength, letter, vowelCount;
textBox = document.getElementById('textBox');
phrase = textBox.value;
phrase = phrase.toLowerCase();
vowelCount = 0;
for (i = 0; i < phrase.length; i += 1) {
letter = phrase[i];
if (letter === 'a' || letter === 'e' || letter === 'i' || letter === 'o' || letter === 'u') {
vowelCount++;
}
}
alert(vowelCount + ' vowels');
var outArea = document.getElementById('outputDiv');
outArea.innerHTML = vowelCount + ' vowels in ' + phrase;
}
function init() {
alert('init vowels');
var countTag = document.getElementById('countBtn');
countTag.onclick = countVowels;
}
window.onload = init();
The problem is window.onload = init();
问题是
window.onload = init();
, here you are calling init
method and is assigning the value returned by init
as the onload
callback. ,这里您正在调用
init
方法,并将init
返回的值分配为onload
回调。 So when the init
method is called the countBtn
is not yet added to the dom resulting in an error like Uncaught TypeError: Cannot set property 'onclick' of null
. 因此,当调用
init
方法时, countBtn
尚未添加到dom中,从而导致类似Uncaught TypeError: Cannot set property 'onclick' of null
的错误Uncaught TypeError: Cannot set property 'onclick' of null
。
What you really want is to call init
on the load
event, so you need to pass the reference to init
function to onload
您真正想要的是在
load
事件上调用init
,因此您需要将对init
函数的引用传递给onload
It should be 它应该是
window.onload = init;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.