如何使用功能开关按类名可见?

时间:2017-10-16 19:20:13

标签: javascript html css

我正在尝试使用函数switchVisible来使用纯JavaScript。我目前使用getElementById工作,但是我想要显示多个元素并在单击按钮时隐藏。

现在我的javascript看起来像

function switchVisible() {
    if (document.getElementById('locked')) {
        if (document.getElementById('locked').style.display == 'none') {
            document.getElementById('locked').style.display = 'inline-block';
            document.getElementById('unlocked').style.display = 'none';
        }
        else {
            document.getElementById('locked').style.display = 'none';
            document.getElementById('unlocked').style.display = 'inline-block';
        }
    }
}

CSS

#unlocked {
    display: none;
}

HTML

<input id="edit-invoice" type="button" value="Edit Invoice" onclick="switchVisible();" />

<p id="locked" class="locked">anexample.pdf</p>
<input id="unlocked" class="unlocked" type="text" placeholder="anexample.pdf">

到目前为止这是有效的,但它只能针对一个元素,因为它是由Id。我怎么能拿这个脚本并更改它,这样我就可以按类名来定位元素,这样我就可以在点击按钮时隐藏和显示多个元素?

2 个答案:

答案 0 :(得分:0)

您可以按类名

定位多个元素

function switchVisible() {

  // Get locked and unlocked elements by class name
  let lockedElems = document.querySelectorAll(".locked");
  let unlockedElems = document.querySelectorAll(".unlocked");

  // Loop through locked elements
  Array.prototype.map.call(lockedElems, function(locked, index) {
  
    // Get current unlocked element
    let unlocked = unlockedElems[index];
    
    // Do your thing
    if (locked) {
      if (locked.style.display == "none") {
        locked.style.display = "inline-block";
        unlocked.style.display = "none";
      } else {
        locked.style.display = "none";
        unlocked.style.display = "inline-block";
      }
    }
    
  });
}
.unlocked {
  display: none;
}
<input id="edit-invoice" type="button" value="Edit Invoice" onclick="switchVisible()" />

<p class="locked">anexample.pdf</p>
<input class="unlocked" type="text" placeholder="anexample.pdf">

<p class="locked">anexample.pdf</p>
<input class="unlocked" type="text" placeholder="anexample.pdf">

<p class="locked">anexample.pdf</p>
<input class="unlocked" type="text" placeholder="anexample.pdf">

答案 1 :(得分:0)

使用getElementsByClassName并循环结果。

function switchVisible() {
    var locked = getElementsByClassName('locked');
    for (var i = 0; i < locked.length; i++) {
        if (locked[i].style.display == 'none') {
            document.getElementById('locked').style.display = 'inline-block';
            locked[i].nextElementSibling.style.display = 'none';
        }
        else {
            locked[i].style.display = 'none';
            locked[i].nextElementSibling.style.display = 'inline-block';
        }
    }
}