简体   繁体   English

我是es6 javascript的新手

[英]i'm new in es6 javascript

 const name = document.getElementById('fname'); const submit = document.getElementById('submit'); const out = document.getElementById('out'); const gname = name.value; // greet function const greet = (n) => { return `hello ${n}`; }; // output const pout = (fname) => { out.innerHTML = greet(fname); }; // call event submit.addEventListener("click", () => { pout(gname) }); 
 <input type="text" id="fname" placeholder="Please enter your name"><br> <button id="submit" >Submit</button> <br><br> OUTPUT: <span id="out"></span> 

Please help me to find the error in the code, i'm learning es6 JavaScript, can't find the error 请帮助我找到代码中的错误,我正在学习es6 JavaScript,找不到错误

I am assuming you want to display the value of the input on output . 我假设您要在output上显示输入的值。 In that case, you should be passing name.value to the greet() function! 在这种情况下,您应该将name.value传递给greet()函数!

I have removed the gname constant, as they are not needed here. 我删除了gname常量,因为这里不需要它们。 However, you may instead move gname within the output function since it is only needed within the function, and not anywhere else. 但是,您可以在output函数中移动gname,因为仅在函数中需要它,而在其他任何地方都不需要。

 const name = document.getElementById('fname'); const out = document.getElementById('out'); const submit = document.getElementById('submit'); // greet function const greet = (n) => { return `hello ${n}`; }; // output const pout = () => { out.innerHTML = greet(name.value); }; // call event submit.addEventListener("click", (event) => { pout(); }); 
 <input type="text" id="fname" ><br> <button id="submit" >Submit</button> <br><br> OUTPUT: <span id="out"></span> 

The gname is assigned the input element value - const gname = name.value; gname分配了输入元素值const gname = name.value; and your input element is empty initially. 并且您的input元素最初为空。 So everytime you call pout(gname) , gname will have empty string. 因此,每次调用pout(gname) ,gname都会有一个空字符串。 If you want to pass the entered value in input, pass name.value and not gname . 如果要在输入中传递输入的值,请传递name.value而不是gname

submit.addEventListener("click", () => { pout(name.value) });

 const name = document.getElementById('fname'); const submit = document.getElementById('submit'); const out = document.getElementById('out'); // greet function const greet = (n) => { return `hello ${n}`; }; // output const pout = (fname) => { out.innerHTML = greet(fname); }; // call event submit.addEventListener("click", () => { pout(name.value) }); 
 <input type="text" id="fname" placeholder="Please enter your name"><br> <button id="submit">Submit</button> <br><br> OUTPUT: <span id="out"></span> 

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

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