【问题标题】:jQuery Counter Not WorkingjQuery 计数器不工作
【发布时间】:2014-11-08 03:25:26
【问题描述】:

这里是 JavaScript/jQuery 新手!

我这里有以下表格(使用引导程序的禁用类,请注意):

编辑:“禁用”类是引导程序中的一个东西,如果按钮存在或不存在,它会正确禁用和启用按钮。

<form action="" method="post">
<input type="text" id="bio">
<p class="bio-counter"></p>
<input type="text" id="username">
<p class="user-counter"></p>
<input type="submit" class="btn">
</form>

还有以下脚本(我已经正确地在我的 head 标签中包含了 jQuery):

var main = function() {
   $('.bio-counter').text('500');
   $('.user-counter').text('0');
   var postLengthUser = $('#username').val().length;
   var postLengthBio = $('#bio').val().length;
   $('#username').keyup(function() {
     $('.user-counter').text(postLengthUser);
   });
   $('#bio').keyup(function() {
    var charactersLeftBio = 500 - postLengthBio;
    $('.bio-counter').text(charactersLeftBio);
  });
  if(postLengthUser > 6 && postLengthUser < 21) {
    if(postLengthBio >= 0 && postLengthBio < 501) {
      $('.btn').removeClass('disabled');
    } else {
      $('.btn').addClass('disabled');
    }
  } else {
    $('.btn').addClass('disabled');
  }
}

$(document).ready(main);

我遇到了以下问题:

  • 即使我在输入中输入了足够多的信息,“btn”也不会失去其禁用状态。
  • 计数器未更新。

我做错了什么?

【问题讨论】:

  • 尝试将函数放入 $(document).ready(function( 而不是在变量中调用它
  • 你不使用 removeClass 和 AddClass 作为属性
  • @Markipe 类 'disabled' 是引导程序中的一个东西,如果按钮存在或不存在,它会正确禁用和启用按钮。
  • @AbdulAhmad 那没用。据我所知,这并没有什么不同。

标签: javascript jquery html twitter-bootstrap


【解决方案1】:
<script>
    var main = function () {
        var postLengthUser = 0;
        var postLengthBio = 0;

        $('.bio-counter').text(500);
        $('.user-counter').text(0);


        var validate = function () {
            if (postLengthUser > 6 && postLengthUser < 21) {
                if (postLengthBio >= 0 && postLengthBio < 501) {
                    $('.btn').removeClass('disabled');
                } else {
                    $('.btn').addClass('disabled');
                }
            } else {
                $('.btn').addClass('disabled');
            }
        }

        $('#username').keyup(function () {
            postLengthUser = $('#username').val().length;
            $('.user-counter').text(postLengthUser);

            validate();
        });

        $('#bio').keyup(function () {
            postLengthBio = $('#bio').val().length;
            var charactersLeftBio = 500 - postLengthBio;
            $('.bio-counter').text(charactersLeftBio);

            validate();
        });

        validate();
    }

    $(document).ready(main);
</script>
  1. 您仅在页面加载时验证禁用条件,它应该在每个 keyup 事件中运行 - 我将其移至验证功能。

  2. postLengthUser 和 postLengthBio 也仅在页面加载时更新。它们也应该在每个按键事件中更新。

【讨论】:

  • 这不起作用,但我认为这可能是因为变量范围问题。
  • 我运行了这段代码,它对我来说似乎工作正常。您是复制粘贴还是尝试修复您的代码?
【解决方案2】:

尝试使用:

$('.btn').prop('disabled', true);

$('.btn').prop('disabled', false);

改为。

【讨论】:

  • 不工作,同样的问题仍在发生。不过还是谢谢你的建议。 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多