var cityToCheck = document.getElementById("text").value;
var btn = document.querySelector("button");
btn.addEventListener('click', add);
function makeCapital(str) {
var firstChar= str.slice(0,1);
var otherChars = str.slice(1);
firstChar = firstChar.toUpperCase();
otherChars = otherChars.toLowerCase();
var cappedString = firstChar + otherChars;
return cappedString;
}
function add() {
cityToCheck = makeCapital(cityToCheck);
console.log(cityToCheck);
}
我正在努力理解创建函数然后在程序中其他地方使用它的概念,有人告诉我我的代码有什么问题以及为什么我得到一个空字符串而不是其中的大写值我输入的文本框?尽管我花了很多时间试图让它发挥作用,但我显然误解了整个概念
谢谢大家
最佳答案
而不是在定义变量 cityToCheck 时调用该值,只需调用 add() 函数 block 内的值(当触发按钮事件时)。它正在工作。
var cityToCheck = document.getElementById("text");
var btn = document.querySelector("button");
btn.addEventListener('click', add);
function makeCapital(str) {
var firstChar = str.slice(0,1);
var otherChars = str.slice(1);
firstChar = firstChar.toUpperCase();
otherChars = otherChars.toLowerCase();
var cappedString = firstChar + otherChars;
console.log(cappedString);
return cappedString;
}
function add() {
cityToCheck = makeCapital(cityToCheck.value);
}
关于javascript - 如何在另一个 JavaScript 中创建并使用自己的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63223506/