为什么这个函数与布尔变量不起作用?

时间:2021-10-09 21:58:45

I wrote simple code to show/hide some layers after clicking buttons (5 in total) and to change color of the clicked buttons. That works fine. But then I wanted to show a certain element - an arrow - only after clicking first button using a boolean variable and it's not working, the if statement never returns first (hooray) part. What am I missing?

我编写了简单的代码,在单击按钮(总共5个)后显示/隐藏一些图层,并更改单击按钮的颜色。这很好。但后来我想显示一个元素 - 一个箭头 - 只有在使用布尔变量点击第一个按钮后它才能工作,if语句永远不会返回第一个(hooray)部分。我错过了什么?

var click01 = false;

function allowright1() {
  if (click01 == true) {
    console.log('hoooray');
    $('#right_arrow').removeClass('hidden').addClass('visible');
  } else {
    console.log('not working');
  }
};

$('#tile1_p1').click(function() {
  if ($('#1layers1').css('display') == 'none') {
    $('#1layers2, #1layers3, #1layers4, #1layers5').removeClass('block').addClass('none');
      $('#tile2_p1, #tile3_p1, #tile4_p1, #tile5_p1').removeClass('orange');
      $('#1layers1').removeClass('none').addClass('block'); $('#tile1_p1').removeClass('white').addClass('orange');
      var click01 = true; 
      console.log('click01 ' + click01); 
      allowright1();
    }
    else if ($('#1layers1').css('display') == 'block') {
      $('#1layers1').removeClass('block').addClass('none');
      $('#tile1_p1').removeClass('orange').addClass('white');
    }
  });

1 个解决方案

#1


4  

You are not resassigning the top level variable click01.

您没有重新分配*变量click01。

By specifying var click01 = true; you are declaring a variable inside of your click handler that is different to the top level variable. If you remove the var it should work for you, e.g.

通过指定var click01 = true;您在单击处理程序中声明一个与*变量不同的变量。如果您删除var,它应该适合您,例如

$(...).click(function() {
  ...
  click01 = true; // by removing var we reassign the top level variable
  ...
});

#1


4  

You are not resassigning the top level variable click01.

您没有重新分配*变量click01。

By specifying var click01 = true; you are declaring a variable inside of your click handler that is different to the top level variable. If you remove the var it should work for you, e.g.

通过指定var click01 = true;您在单击处理程序中声明一个与*变量不同的变量。如果您删除var,它应该适合您,例如

$(...).click(function() {
  ...
  click01 = true; // by removing var we reassign the top level variable
  ...
});