我是es6 javascript的新手

时间:2019-07-04 02:49:44

标签: javascript html

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,找不到错误

2 个答案:

答案 0 :(得分: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 :(得分:1)

gname分配了输入元素值-const gname = name.value;,而您的input元素最初为空。因此,每次调用pout(gname)时,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>