这只是counter
的一个字符textarea
(稍后我会计算单词)。
未定义currentLenght
变量。我试图在全局和本地范围内使用它,但我得到了同样的错误。
点击左侧跨度后,会调用getCharLenght
fn,并应更新"结果"跨越价值。
这是JS:
getCharacters.addEventListener("click", getCharLenght());
function getCharLenght() {
contentBox.addEventListener("input", function() {
if (currentLength > 0) {
result.innerHTML = currentLength;
result.style.opacity = 1;
} else {
result.style.opacity = 0;
}
});
}
这是笔:
https://codepen.io/damianocel/pen/LLwvBL
为什么会发生这种情况,我知道提升和范围(或多或少)。
答案 0 :(得分:2)
currentLength是在加载时定义的,在此之后不会更新,这意味着它始终是相同的值。
因此,请参阅下面我如何将其移至getCharLenght方法。
var contentBox = document.getElementById("contentBox");
var getCharacters = document.getElementById("getCharacters");
var result = document.getElementById("result");
function getCharLenght() {
var currentLength = contentBox.value.length;
if (currentLength > 0) {
result.innerHTML = currentLength;
result.style.opacity = 1;
} else {
result.style.opacity = 0;
}
}
getCharacters.addEventListener("click", getCharLenght);
此外,当您使用getCharLength()时,它会将其视为执行,并将结果传递给函数本身而不是回调。
请参阅:Callback function - use of parentheses
希望这有帮助。
答案 1 :(得分:1)
问题是在初始化 currentLength中的长度之前调用函数 getCharLenght(), 我已更新您的Codepen,
这是
https://codepen.io/shohil06/pen/brbbvV
var getCharacters = document.getElementById("getCharacters");
var result = document.getElementById("result");
getCharacters.addEventListener("click", getCharLenght());
function getCharLenght() {
contentBox.addEventListener("input", function() {
var contentBox = document.getElementById("contentBox");
var currentLength = contentBox.value.length;
if (currentLength > 0) {
result.innerHTML = currentLength;
result.style.opacity = 1;
} else {
result.style.opacity = 0;
}
});
}
享受!
希望有所帮助
谢谢
答案 2 :(得分:0)
var contentBox = document.getElementById("contentBox");
var getCharacters = document.getElementById("getCharacters");
var result = document.getElementById("result");
var currentLength = 0;
getCharacters.addEventListener("click", getCharLenght());
function getCharLenght() {
contentBox.addEventListener("input", function() {
currentLength = contentBox.value.length
if (currentLength > 0) {
result.innerHTML = currentLength;
result.style.opacity = 1;
} else {
result.style.opacity = 0;
}
});
}
h1 {
color: grey;
margin: 0 auto;
text-align: center;
}
#contentBox {
display: block;
margin: 10px auto;
height: 150px;
width: 50%;
box-shadow: 2px 3px 4px grey;
}
#getCharacters {
border: 1px grey solid;
padding: 5px;
box-shadow: 2px 3px 4px grey;
transition: .3s;
}
#getCharacters:hover {
border: 1px grey solid;
padding: 5px;
box-shadow: 2px 3px 4px blue;
cursor: pointer;
}
#result {
opacity: .2;
transition: .4s;
color: red;
}
<h1> Character counter, enter you text to the text area below </h1>
<textarea id="contentBox"></textarea>
<span id="getCharacters">Click to get the character count</span>
<span id="displayCharacters">There are <span id="result"> ?</span> characters in the text area</span>
试试这个..实际上你只在NaN时读取当前长度一次..之后你没有更新变量..因为你总是在Else
部分结束。