【问题标题】:JavaScript if statement with some Boolean only works first time带有一些布尔值的 JavaScript if 语句仅在第一次工作
【发布时间】:2017-06-14 08:10:49
【问题描述】:

我有这两个函数,第一个(move_c(i))在用户点击(源)图像时运行,第二个(move_to_c1(i))在用户点击(目的地)时运行分区。

还有一个布尔值 (cp),每次运行第二个函数时都会在真假之间翻转。

图像是红色或黄色的,想法是红色只会在 cp == true 时移动,黄色只会在 cp == false 时移动,但它只在第一次工作,之后就失败了它的工作,我不明白为什么。

红色必须先走。第一步,if 条件有效,红色 && true。黄色 && true 第一步不移动(这是正确的)。但对于后续移动,if 条件不起作用。

You can see it in action here.

And the code is here.

哦...我只在圆形游戏上实现了这一点,而不是在方形游戏上。

var cp = true;
function move_c(i) {
  alert(document.getElementById(i).className + " " + cp);
  this.image_c = i;
  if (((document.getElementById(i).className == 'red') && (cp == true)) || ((document.getElementById(i).className == 'yellow') && (cp == false))) {
    c1.setAttribute('onclick', 'move_to_c1(image_c)');
    c2.setAttribute('onclick', 'move_to_c2(image_c)');
    c3.setAttribute('onclick', 'move_to_c3(image_c)');
    c4.setAttribute('onclick', 'move_to_c4(image_c)');
    c5.setAttribute('onclick', 'move_to_c5(image_c)');
    c6.setAttribute('onclick', 'move_to_c6(image_c)');
    c7.setAttribute('onclick', 'move_to_c7(image_c)');
    c8.setAttribute('onclick', 'move_to_c8(image_c)');
    c9.setAttribute('onclick', 'move_to_c9(image_c)');
  }
}

function move_to_c1(i) {
  if (document.getElementById(i).name == 'c' || document.getElementById(i).name == 'c2' || document.getElementById(i).name == 'c4' || document.getElementById(i).name == 'c5') {
    document.getElementById("c1").appendChild(document.getElementById(i));
    document.getElementById(i).style.zIndex = 1;
    document.getElementById(i).setAttribute('name', 'c1');
    cp = !cp;
  }
}

【问题讨论】:

  • cp 总是布尔值吗?那么您不需要检查布尔值。
  • 我喜欢叛逆的布尔值。 “不,我不想说真话!”
  • 另外,你为什么要设置onclick属性,什么时候可以添加事件监听器?
  • cp 始终是布尔值,git hub 刚刚更新,因此您现在可以查看它,不确定事件侦听器,不了解它们
  • 之后它无法完成工作你能解释一下吗?我试过你的应用,它似乎工作。

标签: javascript if-statement boolean


【解决方案1】:

我建议您在 Chrome 中打开您的页面,并使用开发者工具。您可以通过按键盘上的 F12 打开控制台。

在移动第一个笑脸后,控制台将显示move_c 中的c3.setAttribute 行引发了异常。这似乎是因为在移动笑脸时名称 c3 更改为引用多个元素。当它引用多个元素而不是预期的单个元素时,setAttribute 在组中不可用。

解决方法是避免调用c3.setAttribute('onclick', 'move_to_c3(image_c)'); 和类似的已移动/重命名的笑脸。最直接的方法是在每个 setAttribute 之前检查:

if (c1) {
    c1.setAttribute(.....);
}

您可以更改代码以避免为多个对象提供相同的名称。您可以将游戏状态保存在单独的对象中,而不是设置名称属性。在顶部某处添加var gamestate = [];,然后将document.getElementById(i).setAttribute('name', 'c1'); 替换为gamestate[i] = 'c1';。然后您将能够通过访问gamestate[i] 来查找图像的位置。您可以随时使用console.log(gamestate); 记录完整的游戏状态。

请注意,打开控制台后,您可以使用console.log 而不是alert 来查看发生了什么。这比一直确认警报对话框要舒服得多。它还允许您更详细地检查对象的内部,如果您尝试console.log(gamestate);,就会看到。

一旦你完成了这项工作,就可以开始研究数组和 for 循环了。这将有助于通过删除所有重复来简化您的代码。

【讨论】:

  • 另外:一旦 c[1-9] / "onclick" 属性第一次被设置,之后它就不会被取消。这就是为什么他的逻辑只在第一次起作用的原因。实际上条件 if (cp && red || !cp && yellow) 应该发生在 "move_to_cX"
  • @Joel 是的,可能还有更多问题。我只关注最直接的问题,而我的意图更多是介绍开发人员工具。教人钓鱼:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多