[英]I am trying to create a function based on user input. What am I doing with my Code?
[英]My program keeps outputting "undefined". I am trying to create a function that changes text on my webpage with a button that calls a function
我正在嘗試創建一個程序,該程序從 html 獲取用戶輸入並通過 for 循環運行它,然后顯示翻譯后的輸入。 問題是 output 只顯示undefined
。 轉換輸入框中用戶輸入的 function 應該使用 html 中的按鈕調用,但單擊它不會改變任何內容,並且 Z78E6221F6393D1356681DB398F14CED 只是保持“未定義”
function whaleTalk() {
let input = document.getElementById('input').value
const vowels = ['a', 'e', 'i', 'o', 'u'];
let resultArray = [];
for (var i = 0; i < input.length; i++) {
for (var j = 0; j < vowels.length; j++) {
if (input[i] == vowels[j]) {
if (input[i] == 'e') {
resultArray.push('ee');
} else if (input[i] == 'e') {
resultArray.push('uu');
} else {
resultArray.push(input[i]);
}
}
}
}
console.log(resultArray.join('').toUpperCase());
document.getElementById('input').innerHTML = input;
document.getElementById('output').innerHTML = resultArray.join('').toUpperCase();
console.log(resultArray);
}
function translateInput() {
let userInput = document.getElementById('input').value
let translateResult = whaleTalk(userInput);
updateOutput(translateResult);
}
function updateOutput(input) {
document.getElementById('output').innerHTML = input;
}
whaleTalk();
updateOutput();
<!DOCTYPE html>
<head>
<title>Whale Talk Translator</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<link href="whaletranslator.css" rel="stylesheet" type="text/css" />
<style>
</style>
</head>
<body>
<header style="color: white;">Whale Talk Translator </header>
<h2>Input anything you want into the box below and hit the button to translate it.</h1>
<div class="translatorBox">
<input value="" id="input" type="text" class="inputBox" placeholder="Text to translate">
<br>
<div class="container">
<div class="center">
<button class="translateButton" onclick="updateOutput()">Translate</button>
</div>
</div>
<div class="container">
<div class="center">
<button class="reloadButton" onClick="window.location.reload();">Reload</button>
</div>
</div>
</div>
<p style="padding: 2em">Translated input:</p>
<div class="output">
<p id="output"></p>
</body>
<script src="whaletranslator.js" type="text/javascript"></script>
</html>
您的 function 返回 undefined 因為您沒有從中返回任何內容。 嘗試這個:
function whaleTalk() {
let input = document.getElementById('input').value
const vowels = ['a', 'e', 'i', 'o', 'u'];
let resultArray = [];
for (var i = 0; i < input.length; i++) {
for (var j = 0; j < vowels.length; j++) {
if (input[i] == vowels[j]) {
if (input[i] == 'e') {
resultArray.push('ee');
} else if (input[i] == 'e') {
resultArray.push('uu');
} else {
resultArray.push(input[i]);
}
}
}
}
return resultsArray.join('').toUpperCase()
}
現在,當您的translationResult
變量將是您的updateOutput
方法將設置為 id 為“輸出”的元素的 innerHtml 的字符串時
您不滿足方法updateOutput
的參數,“未定義”消息是由於您的調用中未定義參數而導致的
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.