【发布时间】: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.
哦...我只在圆形游戏上实现了这一点,而不是在方形游戏上。
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