Javascript - 切换可见性

时间:2015-03-08 22:27:05

标签: javascript

我想在输入有效时显示一个按钮。 它不起作用,它只显示所有按钮。 这是JavaScript:

        var toggleVisibility = function ()
        {
        hasOccurred = validate(textEntry);

            if (hasOccurred == false) {
            $("addBtn").style.visibility = "visible";
            $("deleteBtn").style.visibility = "hidden"; 
            }
          else if (hasOccurred == true) {
            $("addBtn").style.visibility = "hidden";
            $("deleteBtn").style.visibility = "visible"; 
            }
        }

这是按钮的HTML:

                <button type="button" class="btn btn-success" id="addBtn" oninput="toggleVisibility()"><i class="glyphicon glyphicon-plus-sign"></i> Add to Array</button><br/>
                <button type="button" class="btn btn-danger" oninput="toggleVisibility()" id="deleteBtn"><i class="glyphicon glyphicon-remove-sign"></i> Delete from Array</button><br/>
                <button type="button" class="btn btn-info" id="sumBtn">Sum of Array</button>

1 个答案:

答案 0 :(得分:0)

你正在使用$,如果你正在使用jQuery(但使用不正确的CSS选择器)。如果没有jQuery,您需要document.getElementById("...")

注意:我更改了hasOccurred,以便代码段有效。

var toggleVisibility = function() {
  hasOccurred = false;

  if (hasOccurred == false) {
    document.getElementById("addBtn").style.visibility = "visible";
    document.getElementById("deleteBtn").style.visibility = "hidden";
  } else if (hasOccurred == true) {
    document.getElementById("addBtn").style.visibility = "hidden";
    document.getElementById("deleteBtn").style.visibility = "visible";
  }
}

toggleVisibility();
<button type="button" class="btn btn-success" id="addBtn" oninput="toggleVisibility()"><i class="glyphicon glyphicon-plus-sign"></i> Add to Array</button>
<br/>
<button type="button" class="btn btn-danger" oninput="toggleVisibility()" id="deleteBtn"><i class="glyphicon glyphicon-remove-sign"></i> Delete from Array</button>
<br/>
<button type="button" class="btn btn-info" id="sumBtn">Sum of Array</button>