将Pig Latin JavaScript函数转换为GUI时遇到问题

时间:2020-01-26 06:24:24

标签: javascript html function dom

我被困在我的这个项目上。我有一个在控制台中工作的Pig Latin项目。但是我正在尝试将其转换为GUI。我以为我可以使用已经构建的功能并添加一个输入字段。但这不起作用。

这是我的JS。

const pigLatin = (word) => {

document.getElementById("translate").value;


// Your code here
word = word.trim().toLowerCase();
const vowels = ['a', 'e', 'i', 'o', 'u'];
const myWord = word.split("");
let newWord = "";


if (vowels.includes(myWord[0])) {
myWord.push('yay');
for (let i = 0; i < myWord.length; i++) {
  newWord = newWord + myWord[i];
}
return newWord;
} else {
for (let i = 0; i < myWord.length; i++) {
  if ( (vowels.includes(myWord[i]))) {
    newWord = myWord.slice(i, myWord.length).concat(newWord).join('') + 'ay';
    return newWord;
   } else {
     newWord = newWord.concat(myWord[i])

   }

      }}}

我的HTML

 <body>
<h1>Pig Latin Translator!</h1>
<hr/>
<div id="display-element">

  <input id="translate" type="text" placeholder="Enter word here">
  <button onclick="pigLatin()">Submit</button>
</div>
<hr/>

<div id="output">
</div>


<script src="main.js"></script>

现在我遇到了一个错误:

   Uncaught TypeError:

   Cannot read property 'trim' of undefined
    at pigLatin (main.js:24)
   at HTMLButtonElement.onclick (index.html:13)
       pigLatin @ main.js:24
        onclick @ index.html:13

我要关闭还是需要重新开始?

2 个答案:

答案 0 :(得分:1)

最简单的补丁程序:

-  <button onclick="pigLatin()">Submit</button> 
+  <button onclick="document.getElementById('output').textContent=pigLatin(document.getElementById('translate').value)">Submit</button> 

这当然不是“最佳实践”,但是我想这是您需要的,因为这是一个玩具项目,您只需要它与HTML界面一起使用即可。

通常,您会将两个控件放在一个表单中,并在submitaddEventHandler上附加onsubmit事件处理程序,并在处理程序函数中获取控件值。

答案 1 :(得分:0)

您非常亲密。您的代码中只有很小的错误。

您没有从标记(HTML)中将任何参数传递到pigLatin函数中。在标记中,您具有函数pigLatin(),但没有(word)参数,但是您的JavaScript pigLatin(word)中需要一个参数。这就是为什么当JavaScript尝试执行word.trim()时,word是未定义的,因此它说我无法对trim值执行undefined方法`

这就是你应该做的。

  1. 在JavaScript中,将word参数删除到pigLatin函数中(因为实际上您没有从标记中传递任何东西给它)。
  2. 执行此操作,将word设置为document.getElementById("translate").value;

let word = document.getElementById("translate").value;

这将检索您在输入框中键入的任何值,并将其传递给word

你从那里还好。