简体   繁体   English

如何在Jquery中多次调用一个函数来添加一个事件监听器而不只是监听最后一个?

[英]How to call a function multiple times in Jquery to add an event listener without just listening the last one?

So I want to create a function that counts the characters in a text box and prints the number below it.所以我想创建一个函数来计算文本框中的字符并打印它下面的数字。 The thing is that I want to be able to reutilize the function two times since I have two text boxes.问题是我希望能够重复利用该功能两次,因为我有两个文本框。

  <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>

I want to call this function two times but only the last call to the function works, here's my function.我想调用这个函数两次,但只有最后一次调用该函数有效,这是我的函数。

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);
        }
    })
}

The selector would be the id's of the textbox and the div in one string ej: "#custom_message#charsleft1"选择器将是文本框的 id 和一个字符串 ej 中的 div:“#custom_message#charsleft1”

Assuming you're passing distinct selectors in, the problem is that your code is falling prey to what I call the Horror of Implicit Globals : You need to declare text_box and counter so that they're local to the char_counter_limit function, not globals.假设您传入不同的选择器,问题在于您的代码正在成为我所说的隐式全局恐怖的牺牲品:您需要声明text_boxcounter以便它们是char_counter_limit函数的本地函数,而不是全局变量。 When they're globals, the second call overwrites the first.当它们是全局变量时,第二个调用会覆盖第一个调用。

Put var in front of them:var放在他们前面:

function char_counter_limit(selector, content){
    var text_box = "#"+selector.split("#")[1]
    var counter = "#"+selector.split("#")[2]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM