我是 es6 javascript 新手

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

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>

请帮我找出代码中的错误,我正在学习es6 JavaScript,找不到错误

javascript html dom
2个回答
3
投票

我假设您想在

output
上显示输入的值。在这种情况下,您应该将
name.value
传递给
greet()
函数!

我删除了

gname
常量,因为这里不需要它们。但是,您可以在
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>


1
投票

gname
被分配输入元素值 -
const gname = name.value;
并且您的
input
元素最初为空。所以每次你调用
pout(gname)
时,gname 都会有空字符串。如果您想在 input 中传递输入的值,请传递
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>

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