1

对应的html:

<html>
<title></title>
<head>

</head>
<body>
<FORM NAME="Calculator">
<TABLE BORDER=4>
<TR>
<TD>
<input type="text"   name="Input" Size="22" value="">
<input type="text" name="notepad" value="">
<br>
</TD>
</TR>
<TR>
<TD>
<INPUT TYPE="button" NAME="one"   VALUE="  1  " class ="digit" >
<INPUT TYPE="button" NAME="two"   VALUE="  2  " class ="digit" >
<INPUT TYPE="button" NAME="three" VALUE="  3  " class ="digit" >
<INPUT TYPE="button" NAME="plus"  VALUE="  +  " class ="operand">
<br>
<INPUT TYPE="button" NAME="four"  VALUE="  4  " class ="digit">
<INPUT TYPE="button" NAME="five"  VALUE="  5  " class ="digit">
<INPUT TYPE="button" NAME="six"   VALUE="  6  " class ="digit">
<INPUT TYPE="button" NAME="minus" VALUE="  -  " class="operand">
<br>
<INPUT TYPE="button" NAME="seven" VALUE="  7  " class ="digit">
<INPUT TYPE="button" NAME="eight" VALUE="  8  " class ="digit">
<INPUT TYPE="button" NAME="nine"  VALUE="  9  " class ="digit">
<INPUT TYPE="button" NAME="times" VALUE="  x  " class ="operand">
<br>
<INPUT TYPE="button" NAME="clear" VALUE="  c  " class ="special">
<INPUT TYPE="button" NAME="zero"  VALUE="  0  " class ="digit">
<INPUT TYPE="button" NAME="Execute"  VALUE="  = " class ="solve">
<INPUT TYPE="button" NAME="div"   VALUE="  /  " class ="operand">
<br>
</TD>
</TR>
</TABLE>
</FORM>

<script type = "text/javascript" src="C:\Users\Quonn\Desktop\QBJS\calculatorjs.js">
</script>
</body>
</html> 

javascript:

document.onclick = function(x) {
  var info = x.target;
  if (info.className === "digit" || "operand")
  {
    addDigit();
  }
  else {
    math();
  }
}

function addDigit() {
  alert("x");
}

function math() {
  alert("y");
}

x 是通过单击计算器上的按钮传入的。即使 info.className 不是数字/操作数,if 语句也会返回 true。我需要在 if 语句中更改什么以使其返回 false?

4

3 回答 3

4

您没有||正确使用运算符。

||运算符用于OR两个值。它出现两个值之间。

从你的例子:

首先它检查您的条件的左侧:

info.className === "digit"

如果为true,则||运算符返回true(它不评估右侧)。

否则,它会评估您的条件的右侧:

"operand"

这将始终评估为true,因为字符串“操作数”不等于false

要解决此问题,您需要在运算符的两侧使用正确的表达式||

if (info.className === "digit" || info.className === "operand") {
    alert("Yay");
}
于 2013-02-26T01:53:05.567 回答
1
if (info.className === "digit" || info.className === "operand")
于 2013-02-26T01:53:09.987 回答
0

解释为布尔值的字符串将始终返回 true。

if (info.className === "digit" || "operand") 应该是 if (info.className == "digit" || info.className == "operand")

于 2013-02-26T01:53:56.073 回答