如何声明在onclick函数外单击了一个按钮

时间:2017-07-13 17:24:30

标签: javascript jquery



$(document).ready(function() {
    var status = 'not active';
    $('#button').on('click', function() {
                var button = 'THE BUTTON IS CLICKED';
                var status = 'active';
                alert(button);
     });
      if(status == 'active'){
          alert('THE BUTTON IS ACTIVATED');
      } else {
          alert('THE BUTTON IS NOT ACTIVE');
      }
 });

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="button">X</button>
&#13;
&#13;
&#13;

在我的代码中,我试图让onclick函数旁边的按钮的status输入if statement,但它不会在...之外定义功能完全。我想让alert('THE BUTTON IS ACTIVATED');工作。

1 个答案:

答案 0 :(得分:3)

您正在声明一个名为status的新变量,它会在函数内部“混淆”外部status。只需删除var即可使用外部版本:

$(document).ready(function() {
    var status = 'not active';
    $('#button').on('click', function() {
                var button = 'THE BUTTON IS CLICKED';
                status = 'active';
                alert(button);
     });
      if(status == 'active'){
          alert('THE BUTTON IS ACTIVATED')
      } else {
          alert('THE BUTTON IS NOT ACTIVE');
      }
 });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="button">X</button>

编辑:您的代码有两个奇怪的事情:您只使用状态,警报,一次,文档准备就绪,并且您不切换{{1} } 状态。也许你想要这样的东西(在这个状态下使用布尔变量而不是字符串会更好):

active
$(document).ready(function() {
    var status = 'not active';
    $('#button').on('click', function() {
                var button = 'THE BUTTON IS CLICKED';
                status = (status == 'active') ? 'not active' : 'active';
                alert(button);

                showButtonStatus();
     });

     function showButtonStatus() {
        if(status == 'active'){
          alert('THE BUTTON IS ACTIVATED')
        } else {
          alert('THE BUTTON IS NOT ACTIVE');
        }
     }
 });