当我的代码不仅会提醒一次?

时间:2015-10-19 16:36:28

标签: javascript jquery html

$(document).ready(function(){
  $( "#add_form" ).hide();
});


function checkID(obj) {
  var href = obj.getAttribute('href'); // get link href
  console.log(href);
  if ( $( "#add_form" ).is( ":hidden" ) ) {
      $("#userID").val("");
      $( "#add_form" ).slideDown(500);
      $('<div/>',{                    // create a dynamic overlay div
        id:"overlay"
        }).appendTo("body");
    } 

    $("#submitCheck").on("click", function() {
      var value = $("#userID").val();// user input
        var index = $.inArray(value, ["1234", "5678"])
        alert(index);
        closeForm();
    });
}

function closeForm() {
  $( "#add_form" ).hide();
  $('#overlay').remove();            // remove this overlay when cancel clicked.
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<a href="" onclick="checkID(this); return false;">Click Here</a>
<div class="center">
      <div id="add_form">
          <input type="text" id="userID" name="userID">
          <!-- <br/> -->
          <button type="button" id="submitCheck">comfirm</button>
          <button type="button" id="submitCancel" onclick="closeForm();">Cancel</button>
      </div>  
    </div>

1.当我点击按钮时,表格会弹出,我输入“11”然后警告-1 后退和弹出窗口消失。

2.我再次点击按钮,输入“11”并提醒-1 两次

任何人都知道它为什么会两次返回-1?

1 个答案:

答案 0 :(得分:2)

仅将click事件绑定在submitCheck上一次。为此,请将该代码移到您的函数之外并在DOM Ready callback内部,如下所示。

$(document).ready(function(){
  $("#submitCheck").on("click", function() {
        var value = $("#userID").val();// user input
        var index = $.inArray(value, ["1234", "5678"])
        console.log(index);
        closeForm();
    });
  $( "#add_form" ).hide();
});


function checkID(obj) {
  var href = obj.getAttribute('href'); // get link href
  console.log(href);
  if ( $( "#add_form" ).is( ":hidden" ) ) {
      $("#userID").val("");
      $( "#add_form" ).slideDown(500);
      $('<div/>',{                    // create a dynamic overlay div
        id:"overlay"
        }).appendTo("body");
    } 

    
}

function closeForm() {
  $( "#add_form" ).hide();
  $('#overlay').remove();            // remove this overlay when cancel clicked.
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<a href="" onclick="checkID(this); return false;">Click Here</a>
<div class="center">
      <div id="add_form">
          <input type="text" id="userID" name="userID">
          <!-- <br/> -->
          <button type="button" id="submitCheck">comfirm</button>
          <button type="button" id="submitCancel" onclick="closeForm();">Cancel</button>
      </div>  
    </div>