【发布时间】:2020-04-06 04:34:58
【问题描述】:
所以我想创建一个函数来计算文本框中的字符并打印其下方的数字。问题是我希望能够重复使用该功能两次,因为我有两个文本框。
<textarea id="custom_message" placeholder="sumthin sumthin" maxlength="240"></textarea>
<div id="charsleft1" class="span-8" style="float:right; text-align:right"></div>
<textarea id="restriction_message" placeholder="other sumthing" maxlength="240"></textarea>
<div id="charsleft2" class="span-8" style="float:right; text-align:right"></div>
我想调用此函数两次,但只有最后一次调用该函数有效,这是我的函数。
function char_counter_limit(selector, content){
text_box = "#"+selector.split("#")[1]
counter = "#"+selector.split("#")[2]
var maxlength = $(text_box).attr("maxlength");
$(counter).text(0+" / "+maxlength);
$(text_box).on("input", function(){
var maxlength = $(this).attr("maxlength");
var currentLength = $(this).val().length;
if(currentLength <= maxlength){
$(counter).text(currentLength+" / "+maxlength);
}
})
}
选择器将是文本框的 id 和一个字符串 ej 中的 div:“#custom_message#charsleft1”
【问题讨论】:
-
旁注:您的代码与分号不一致。我强烈建议您决定是依赖 ASI 并省略它会为您修复的分号,还是包含它们,然后可靠地做到这一点。
-
你可能错过了 text_box 和 counter 的 var 声明
标签: javascript jquery forms jquery-selectors