将Pig Latin JavaScript函数转换为GUI遇到麻烦

问题描述 投票:0回答:2

我被困在我的这个项目上。我有一个在控制台中工作的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

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

javascript html function dom
2个回答
0
投票

最简单的补丁:

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

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

通常,您将两个控件放在一个窗体中,并在submit事件处理程序上附加addEventHandleronsubmit,并在处理程序函数中获取控件值。


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

你从那里还好。

© www.soinside.com 2019 - 2024. All rights reserved.