我想在我的文本区域下方添加书面文本的长度。
为此,我定义了一个 span
元素来编写我的 Angular 色。
但是,我目前收到以下错误:
Uncaught ReferenceError: len is not defined
在下面找到我的可行示例:
$(".form-control.description").keyup(this.countCharacters.bind(this))
function countCharacters() {
len = $(".form-control.rigDesc").val().length
$(".remainChar").html("#" + len);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet"/>
<div class="form-group row" align="left">
<div class="col-7">
<textarea class="form-control rigDesc" rows="4" id="comment" placeholder="Describe..."></textarea>
<span class="remainChar"></span>
</div>
</div>
有什么关于如何捕获文本区域字段长度的建议吗?
感谢您的回复!
最佳答案
您在 textarea
中缺少类 description
因为您在您的 $(".form-control.description")
keyup
事件寻找类为 form-control
和 description
的元素,所以你需要添加 description
类你的 textarea
。
$(".form-control.description").keyup(this.countCharacters.bind(this))
function countCharacters() {
len = $(".form-control.rigDesc").val().length
$(".remainChar").html("#" + len);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet"/>
<div class="form-group row" align="left">
<div class="col-7">
<textarea class="form-control description rigDesc" rows="4" id="comment" placeholder="Describe..."></textarea>
<span class="remainChar"></span>
</div>
</div>
为了提高准确性并防止意外错误,您可以使用 $("textarea.form-control.description")
来确保 keyup
事件仅适用于 textarea
类 form-control
和 description
。
$("textarea.form-control.description").keyup(this.countCharacters.bind(this))
function countCharacters() {
len = $(".form-control.rigDesc").val().length
$(".remainChar").html("#" + len);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet"/>
<div class="form-group row" align="left">
<div class="col-7">
<textarea class="form-control description rigDesc" rows="4" id="comment" placeholder="Describe..."></textarea>
<span class="remainChar"></span>
</div>
</div>
关于javascript - 获取文本区域的长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50187113/