如何在没有jQuery的情况下隐藏和显示数组元素

时间:2017-10-30 19:58:21

标签: javascript html css onclick show-hide

所以我有一个数组,我希望能够通过使用vanilla JavaScript单击它来隐藏和显示数组的每个元素。虽然我对如何在这个实例中使用getElementById感到有点困惑,因为它是一个数组......

HTML:

<html>
<head>
  <script src="js/sender.js"></script>
  <link href="css/style.css" rel="style" media="screen">
  <script>
  </script>
</head>

<body>
  <div class="sub" id="main">
  </div>
  <ol id="list"></ol>
  </div>
</body>
</html>

JavaScript的:

var sender:[bob, sally, syke, lucy, larry,];
for(var i =0; i<sender.length; i++){
var liBody = document.createElement("li");
liBody.IdName = "main";
liBody.innerHTML = sender[i]; 
document.body.appendChild(liBody);

}

2 个答案:

答案 0 :(得分:0)

听起来你正在尝试在列表中显示每个数组项,并切换数组项&#39;点击的可见性。如果我正确理解您的问题,可以采用以下方法:

&#13;
&#13;
var sender = ["bob", "sally", "syke", "lucy", "larry"];
var myList = document.getElementById('list');

for (var i = 0; i < sender.length; i++) {
  var liBody = document.createElement("li");
  var spanWrapper = document.createElement("span");  //wrapper to handle the clicks
  spanWrapper.style.display = "block";
  liBody.IdName = "main";
  liBody.innerText = sender[i]; //pulling value from sender array
  liBody.style.visibility = "visible";
  spanWrapper.addEventListener('click', function() { //add click handler
    if (this.childNodes[0].style.visibility == "visible") {
      this.childNodes[0].style.visibility = "hidden";  //hide item
    } else {
      this.childNodes[0].style.visibility = "visible";  //show item
    }
  });
  spanWrapper.appendChild(liBody);  //add list item to its span wrapper
  myList.appendChild(spanWrapper); //add span wrapper to the list
}
&#13;
<div class="sub" id="main">
  <ul id="list"></ul>
</div>
&#13;
&#13;
&#13;

此代码遍历您的sender数组,并将每个数组元素分配给<li>。每个<li>都放在<span>内,以便处理任何点击并将项目切换为可见或隐藏。

点击每个列表项(从sender数组中填充)会隐藏该项目(如果该项目当前可见),或者显示该项目当前是否已隐藏。

除非<li>的{​​{1}}属性用于此处未见的其他目的,否则您可以从代码中删除此行:

IdName

你还有一个额外的liBody.IdName = "main"; 标签不应该存在,除非数组中的名称实际上是变量,否则你的数组声明应该是这样的:

</div>

而不是:

var sender = ["bob", "sally", "syke", "lucy", "larry"];

答案 1 :(得分:-1)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>


<ul id="list"></ul>


<script>
    list = document.getElementById('list');
    items = ['item 0', 'item 1', 'item 2'];
    for (x = 0; x < items.length; x++) {
        li = document.createElement('li');
        li.appendChild(document.createTextNode(items[x]));
        list.appendChild(li);
        list.childNodes[x].setAttribute('onclick', 'hide(' + x + ')');
    }

    function hide(pos) {
        list.childNodes[pos].style.display = 'none';
    }


</script>


</body>
</html>