随机字符总是返回零

时间:2016-12-05 08:40:23

标签: javascript jquery

在这个片段中,它会随机生成混合的单词和数字,但我想知道为什么它总是在第二个字符中返回零?如果单击“刷新”按钮,则始终在第二个位置返回0。任何想法?



$(function() {
  var words = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZ0123456789abcdefghiklmnopqrstuvwxyz"
  var myLength = 4;

  function Captcha() {
    $('#Captcha').html("");
    for (var i = 0; i < myLength; i++) {
      var word = words[Math.floor(Math.random() * words.length)];
      $('#Captcha').append(word + i++);
    }
  }
    Captcha();
 $('#reCaptchaRefresh').click(function(){
  Captcha();
  });
});
&#13;
#Captcha {
border: 1px solid black;
  padding: 10px;
  float: left;
}

#reCaptchaRefresh {
clear: both;  
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="Captcha" ></div>
<div id="reCaptchaRefresh">
Refresh
</div>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:3)

原因是您要将i附加到输出字符串。您还在每次迭代中递增i两次。试试这个:

&#13;
&#13;
$(function() {
  var words = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZ0123456789abcdefghiklmnopqrstuvwxyz"
  var myLength = 4;

  function Captcha() {
    $('#Captcha').empty();

    for (var i = 0; i < myLength; i++) {
      var word = words[Math.floor(Math.random() * words.length)];
      $('#Captcha').append(word); // Note the removal of the concatenation and '++' here
    }
  }

  $('#reCaptchaRefresh').click(Captcha).trigger('click');
});
&#13;
#Captcha {
  border: 1px solid black;
  padding: 10px;
  float: left;
}
#reCaptchaRefresh {
  clear: both;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="Captcha"></div>
<div id="reCaptchaRefresh">
  Refresh
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:2)

i++会导致问题。因为你在每个角色的末尾追加i++。和循环也只会运行2 times

$(function() {
  var words = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZ0123456789abcdefghiklmnopqrstuvwxyz"
  var myLength = 4;

  function Captcha() {
    $('#Captcha').html("");
    for (var i = 0; i < myLength; i++) {
      var word = words[Math.floor(Math.random() * words.length)];
      $('#Captcha').append(word);
                      //   ^^^^^ edited here
    }
  }
    Captcha();
 $('#reCaptchaRefresh').click(function(){
  Captcha();
  });
});
#Captcha {
border: 1px solid black;
  padding: 10px;
  float: left;
}

#reCaptchaRefresh {
clear: both;  
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="Captcha" ></div>
<div id="reCaptchaRefresh">
Refresh
</div>