繁体   English   中英

我很难弄清楚我的html和js文件出了什么问题。 我需要数元音

[英]I am having a hard time figuring out what is wrong with my html and js file. I need to count the vowels

我需要为一个类修复这段代码,并且已经修复了许多问题,但是我不确定为什么它不起作用。 应该计算出短语中的元音数量,并将其作为警报返回。 当我点击按钮时,什么也没有出现。

这是html。 它可以正常工作,但在我丢失某些东西的情况下可以添加

<!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>

这是JS。 它似乎没有在代码末尾注册“ 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();

问题是window.onload = init(); ,这里您正在调用init方法,并将init返回的值分配为onload回调。 因此,当调用init方法时, countBtn尚未添加到dom中,从而导致类似Uncaught TypeError: Cannot set property 'onclick' of null的错误Uncaught TypeError: Cannot set property 'onclick' of null

您真正想要的是在load事件上调用init ,因此您需要将对init函数的引用传递给onload

它应该是

window.onload = init;

演示: 小提琴

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM