javascript - JS和Jquery函数参数未定义

标签 javascript jquery

我正在写一个计数器代码。我有以下需要 4 个参数的函数。 'fieldSelector' 是文本区域的 id 或类选择器,'msgSelector' 是必须显示文本消息的范围。 'min' 和 'max' 是文本的最小和最大限制。

  function updateCountdown(min, max, fieldSelector, msgSelector) {

    alert(msgSelector)

    var chars = jQuery(fieldSelector).val().length;
    var remaining = max - chars;
    if (chars < min){
      var moreChars = min - chars;
      jQuery(msgSelector).addClass('text-danger');
      if (chars == 0)
        jQuery(msgSelector).text('You need to add atleast ' + moreChars + ' characters.');
      else if (chars == min-1)
        jQuery(msgSelector).text('You need to add atleast ' + moreChars + ' more character.');
      else
        jQuery(msgSelector).text('You need to add atleast ' + moreChars + ' more characters.');
    }
    else
    {

      jQuery(msgSelector).removeClass('text-danger');
      if (remaining <=10)
        jQuery(msgSelector).addClass('text-danger');

      if (remaining == 1)
          jQuery(msgSelector).text('You can add only ' + remaining + ' more character.');  
      else if (remaining > 0)
          jQuery(msgSelector).text('You can add ' + remaining + ' more characters.');
      else if (remaining == 0)
        jQuery(msgSelector).text('Your limit has been ended.');
      else if (remaining == -1)
        jQuery(msgSelector).text('You have exceded ' + (-remaining) + ' character.');
      else 
        jQuery(msgSelector).text('You have exceded ' + (-remaining) + ' characters.');

  }
}

我用以下方式调用这部分。

 $(document).ready(function(){


 $('#profile_short_description_textarea').change(updateCountdown(100,150,'#profile_short_description_textarea', '#short_description_message'));
    $('#profile_short_description_textarea').keyup(updateCountdown(100,150,'#profile_short_description_textarea', '#short_description_message'));

});

参数值 min、max、fieldSelector 和 msgSelector 仅在文档​​加载时第一次传递。 min、max 和其他两个参数的值未定义。这段代码有什么问题?

最佳答案

像这样使用

$('#profile_short_description_textarea').change(function() {
    updateCountdown(100, 150, '#profile_short_description_textarea', '#short_description_message');
});
$('#profile_short_description_textarea').keyup(function() {
    updateCountdown(100, 150, '#profile_short_description_textarea', '#short_description_message');
});

关于javascript - JS和Jquery函数参数未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29255314/

相关文章:

jquery - Ipad ( 1 ) : safari keep crashing in my "supersized" slideshow

asp.net - IE7中焦点如何改变输入框的样式?

javascript - 检查 JSON 中的重复项

javascript - 即使定义了函数后,onclick 属性也不起作用

javascript - 如何在 Slack App 中将值从 Slack channel 传递到 `Options Load URL`

javascript - 使用 Webstorm 服务器提供 PHP 服务

javascript - jQuery Find and Replace 正在挂起浏览器!数据量太大?

javascript - 选择要显示和隐藏的 html 类

javascript - 为什么我可以在 JavaScript/TypeScript 中声明变量之前使用它?

javascript - AngularJS 分享功能