【问题标题】:Button assigned with function wont do as i tell it too分配有功能的按钮也不会像我说的那样
【发布时间】:2019-11-17 11:35:30
【问题描述】:

我正在尝试创建一个脚本。目标是用户将 3 个数字放入 3 个框中,然后单击一个按钮以在底部显示的第四个框中显示最大的数字。

由于某种原因,我创建的代码没有按照我写的那样做,我不明白为什么。任何关于问题所在的提示,以便我自己深入研究,我们将不胜感激!

这是浏览器中的实时视图,以便您可以看到当我按下按钮时会发生什么。

https://gyazo.com/1f825e84930891f8727aed6032b94edd

function checkNumbers(){

    //(Check all the numbers the user put in)
    var box1 = document.getElementById("userFill1").value*1;
    var box2 = document.getElementById("userFill2").value*1;
    var box3 = document.getElementById("userFill3").value*1;

//(If box1 > b2 & b3 write box1 value in "answer")
if(box1 > box2 && box3){
document.getElementById("answer").value = box1;
}

//(Same as above but with box 2)
else if(box2 > box1 && box3){
    document.getElementById("answer").value = box2;
}

//(Same as above but with box 3)
else if(box3 > box1 && box2){
    document.getElementById("answer").value = box3;
}

//(If no statements above is true, alert this)
else{
    alert("Vänligen fyll i med endast siffror och olika värden i varje fält");
}

}

【问题讨论】:

  • 好吧,我以某种方式解决了这个问题,我所做的是这个 else if(box2 > box3 && box1) else if(box3 > box1 && box2) 旋转了 else if 语句中的数字,为什么会这样完成这项工作?

标签: javascript function if-statement button assign


【解决方案1】:

只需使用 document.getElementById("answer").value = Math.max(box1,box2,box3) 而不是所有这些 ifology

【讨论】:

  • 您好,Math.max 还不是我们一直在研究的东西,我怀疑如果我们只知道这些其他方式,我们所有的作业都可以以更快更好的方式完成。我认为他们希望我们根据我们最近的情况来解决问题,如果这有意义的话。
【解决方案2】:

Niqqo 问题在于您如何比较变量,在您的第一个 if 中,您正在检查 box1 是否大于 box2 以及 如果 box3 不是 0。你真正想做的是if(box1 > box2 && box1 > box3)。我了解到您尝试比较 box1 是否大于 box2 并同时大于 box3,但这是不可能的,您必须拆分条件。

if 语句中,您必须非常清楚在哪个条件下。

【讨论】:

  • 我不确定为什么我不能同时检查 box1 是否大于 box2 和 3。这只是“它是怎么回事”还是有一个很好的解释为什么这不可能像我那样做? :) 干杯! :)
  • 是的......实际上它就是这样工作的,你就是不能。没问题的哥们!希望你能解决你的问题!
猜你喜欢
  • 2014-08-19
  • 1970-01-01
  • 2013-11-13
  • 1970-01-01
  • 1970-01-01
  • 2011-09-25
  • 2012-06-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多