gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 21:59:32 24 4
gpt4 key购买 nike

我被我的这个项目困住了。我有一个在控制台中运行的 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

我已经接近了还是需要重新开始?

最佳答案

最简单的补丁:

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

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

通常,您会将两个控件放入表单中,并使用 addEventHandleronsubmit 附加 submit 事件处理程序,并获取控件值在处理函数中。

关于javascript - 将 Pig Latin JavaScript 函数转换为 GUI 时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59916056/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com