Jquery代码验证代码

时间:2016-04-13 06:00:25

标签: jquery

我需要此代码来检查访问密钥是否正确,当此人输入错误密钥超过3次时,它将显示已过期或转到另一页。

我不知道自己做错了什么,因为我无法对错误尝试进行编码,但是如果有人帮助我仍然没有工作吗?

$(document).ready(function(){
    var acc = 7829;
    var AccessKey = $('#AccessKey').val();

    $("#accessBTN").click(function(){
        if(AccessKey == acc){

        $('#TokenVf').attr("style", "display:none");
        $('#infotf').text("Your access is granted to click continue to proceed to payment.");
        $('#statustf').html("<font color='green'>Verified Access</font>");
        $("#TokenGO").toggle(1000);

        }
        else{
        $('#statustf').html("<font color='red'>Error</font>");  
        $('#infotf').html("<font color='red'>Please correct your access code and try again</font>");
        $('#AccessKey').addClass('surname text error');
        }
    });
});

这是HTML

<div id="statustf"></div><br/>

    

2 个答案:

答案 0 :(得分:1)

页面加载后正在执行var AccessKey = $('#AccessKey').val();,而不是在您单击按钮时执行。将它放在$("#accessBTN").click(function(){块内,这样每次从访问按钮触发点击时,它都会实际检查密码。在原始代码中,输入值仅在页面加载时检查,并且稍后不会更新..

$(document).ready(function(){
    var acc = 7829;        

    $("#accessBTN").click(function(){
        var AccessKey = $('#AccessKey').val(); //<-- here
        if(AccessKey == acc){

            $('#TokenVf').attr("style", "display:none");
            $('#infotf').text("Your access is granted to click continue to proceed to payment.");
            $('#statustf').html("<font color='green'>Verified Access</font>");
            $("#TokenGO").toggle(1000);

        } else {
            $('#statustf').html("<font color='red'>Error</font>");  
            $('#infotf').html("<font color='red'>Please correct your access code and try again</font>");
            $('#AccessKey').addClass('surname text error');
        }
    });
});

答案 1 :(得分:1)

像这样......

$(document).ready(function() {
  
  var check = 0;

  $("#accessBTN").click(function() {
    var acc = 7829;
    var AccessKey = $('#AccessKey').val();
    //alert(AccessKey+acc)
    if (AccessKey == acc && check < 3) {

      $('#TokenVf').attr("style", "display:none");
      $('#infotf').text("Your access is granted to click continue to proceed to payment.");
      $('#statustf').html("<font color='green'>Verified Access</font>");
      $("#TokenGO").toggle(1000);

    } else {
      $('#statustf').html("<font color='red'>Error</font>");
      $('#infotf').html("<font color='red'>Please correct your access code and try again</font>");
      $('#AccessKey').addClass('surname text error');
      check++
    }
    if (check > 3) {
      alert("'expired'")
    }

  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>

<input type="text" id="AccessKey" />
<button id="accessBTN">access</button>
<div id="statustf"></div>
<br/>