gpt4 book ai didi

javascript - 无法从 html 文本框获取实时字数

转载 作者:行者123 更新时间:2023-11-30 16:26:35 25 4
gpt4 key购买 nike

我对 html 和 javascript 很陌生。我有一个文本框,正在尝试计算字数,然后实时显示计数。我不明白我在这方面做错了什么,或者如何纠正它。 textContent 对我来说意义不大。

<html>
<head>
<style>
input[type='text'] {width:50px;}
textarea {width:500px;height:300px;}
</style>
</head>
<body>
<div>
<h2>Test</h2>
<p>The number of words is <span id="wordCount"></span></p>
<textarea id="toCount"></textarea>
</div>
<script>

document.getElementById('toCount').addEventListener('input', function () {
var text = this.textContent,

count = text.trim().replace(/\s+/g, ' ').split(' ').length;

document.querySelector('.wordCount').textContent = count;

});
</script>
</body>
</html>

我现在得到的错误是未捕获的 TypeError:无法将属性“textContent”设置为 null

最佳答案

您的选择器应该是#wordCount,可以使用值访问文本区域内容:

<html>
<head>
<style>
input[type='text'] {width:50px;}
textarea {width:500px;height:300px;}
</style>
</head>
<body>
<div>
<h2>Test</h2>
<p>The number of words is <span id="wordCount"></span></p>
<textarea id="toCount"></textarea>
</div>
<script>

document.getElementById('toCount').addEventListener('input', function () {
var text = this.value,
count = text.trim().replace(/\s+/g, ' ').split(' ').length;
document.getElementById('wordCount').textContent = count;

});
</script>
</body>
</html>

关于javascript - 无法从 html 文本框获取实时字数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34057103/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com