我正在尝试为文本输入字段完成实时字符计数器,但似乎无法使其正常工作。 onkeypress函数要么未定义,要么在加载页面时被调用一次]
仅用onkeypress =“”分配功能似乎不起作用。
此外,我想更新charcountLabel的文本;我似乎无法做到。简单地使用'document.getElementById'更新其innerHTML无效。
请参见下面的代码:
<input type="text" id="textContent" onkeypress="charcount">
// Should be live-updated with the length of input text above.
<span id="charcountLabel"> 0 </span>
<script>
function charcount() {
var characterCount = document.getElementById("textContent").innerText.length;
document.getElementById("charcountLabel").innerHTML = characterCount;
}
</script>
您在这里
<input type="text" id="textContent" onkeypress="charcount()">
<!-- Should be live-updated with the length of input text above. -->
<span id="charcountLabel">0</span>
<script>
function charcount() {
var characterCount = document.getElementById("textContent").value.length;
document.getElementById("charcountLabel").innerHTML = characterCount;
}
</script>
使用括号()
调用该函数,并将innerText
替换为value
属性。请注意,//
在Javascript中是注释,而不是在HTML中应使用<!-- your comment -->
的注释。最后,它与ejs无关。