我的目标是将 keycount 放在 text_area 上方的空白“p”元素中。这是我的 erb 和 javascript:
<div class="field">
<p id="char-limit"></p>
<%= f.label :essay %><br>
<%= f.text_area :essay, :id => "essay-form" %>
</div>
(顺便说一句,这就是我的javascript文件中的全部内容)
$("#essay-form").on("keyup", function() {
var charCount = $("#essay-form").val().length;
//The text in the p element with id char-limit is equivelent to num of chars
$("#char-limit").html(charCount);
if (charCount > 10) {
$("#char-limit").css("color", "red");
} else {
$("#char-limit").css("color", "black");
}
});
唯一的问题是,当我开始输入时,char-limit p 元素中没有添加字符数。