javascript对一个if语句的多个动作

时间:2016-02-20 19:40:24

标签: javascript

我想做的事情可以这样概括:“如果满足这个条件,那么请执行以下多项操作。”我的代码可以正常工作,但是当我添加要执行的其他操作时,我收到“未捕获的SyntaxError:Unexpected token else”错误。我会注意下面的问题。

function turnonall(cl) {
    var elements = document.getElementsByClassName(cl);
      for (var i = 0; i < elements.length; i++){
        if (elements[i].style.display == 'none' || elements[i].style.display == '' || elements[i].style.display == 'block')
        elements[i].style.display = 'block';
        elements[i].style.className = 'buttonactive';  <--this line is throwing the error.
        else
        elements[i].style.display = 'none';
      }
  }

2 个答案:

答案 0 :(得分:0)

function turnonall(cl) {
    var elements = document.getElementsByClassName(cl);
      for (var i = 0; i < elements.length; i++){
        if (elements[i].style.display == 'none' || elements[i].style.display == '' || elements[i].style.display == 'block')
        {  // Bracket!
            elements[i].style.display = 'block';
            elements[i].style.className = 'buttonactive';  <--this line is throwing the error.
        }  // Bracket!
        else
            elements[i].style.display = 'none';
      }
  }

答案 1 :(得分:0)

您的if/else声明的签名不正确。您尝试的内容仅适用于if/else语句中带有一行的if语句。向无括号if/else添加多行后,括号必需

只需将if和else块包装在括号中,如下所示:

function turnonall(cl) {
  var elements = document.getElementsByClassName(cl);
  for (var i = 0; i < elements.length; i++) {
    if (elements[i].style.display == 'none' || elements[i].style.display == '' || elements[i].style.display == 'block') {
      elements[i].style.display = 'block';
      elements[i].style.className = 'buttonactive';
    } else {
      elements[i].style.display = 'none';
    }
  }
}

然而,你不是100%不正确。例如,这是有效的JavaScript:

if (true)
  console.log('it is true')
else
  console.log('it is not true')

但这不是

if (true)
  console.log('it is true')
  console.log('and I like it')
else
  console.log('it is not true')