为每个新循环添加新ID

时间:2014-05-29 20:35:04

标签: javascript loops

我正在使用li标签开发一种循环。对于这个循环,我将使用一些文本,这些文本将通过一个简单的打开和关闭JavaScript代码显示,这些代码是我在点击某个地方时创建的。大家都知道,这种代码是通过getElementById属性来操纵的。但是,由于我要循环这些列表项,我不能在它们中重复ID。那么,如何在不重复ID的情况下循环这些列表项呢?

采用以下HTML:

<section class="pro-further">
  <span>Consulte</span><br>
  <ul>
    <li><div onClick="furtherInfo('test');">Info one</div>
      <div id="test">Text for first info</div>
    </li>
    <li><div>Info two</div>
      <div>Text for second info</div>
    </li>
    <li><div>Info three</div>
      <div>Text for third info</div>
    </li>
    <li><div>Info four</div>
      <div>Text for fourth info</div>
    </li>
    <li><div>Info five</div>
      <div>Text for fifth info</div>
    </li>
    <li><div>Info six</div>
      <div>Text for sixth info</div>
    </li>
  </ul>
</section>

JavaScript ......

var furtherInfo = function(auei) {
  var openInfo = document.getElementById(auei);
  if(openInfo.style.display == "block") {
    openInfo.style.display = "none"
  }else {
    openInfo.style.display = "block"
  }
}

和CSS

.pro-further ul {
  width:100%;
  list-style-type:none;
  margin-left:0px;
}

.pro-further ul li > div {
  width:99.3%;
  font-size:14px;
  color:#FFF;
  background:url(../images/plus2.png) #23459F no-repeat 99% 50%;
  padding:6px 2px 6px 5px;
  margin-bottom:3px;
  cursor:pointer;
}

.pro-further ul li > div + div {
  width:98.5%;
  font-size:13px;
  color:#737373;
  background:white;
  border:1px solid #23459F;
  padding:2px 5px 2px 5px;
  margin-top:-3px;
  display:none;
  cursor:text;
}

谢谢!

Check here to try out

3 个答案:

答案 0 :(得分:2)

您可以为每个项目提供一个类,然后使用document.getElementsByClassName()

循环遍历它们

在此处查看更多信息: How to getElementByClass instead of GetElementById with Javascript?

答案 1 :(得分:1)

在这种情况下,您可以使用DOM遍历,假设兄弟关系是不变的:

var furtherInfo = function(el) {
    var openInfo = el.nextElementSibling;
  openInfo.style.display = openInfo.style.display == 'block' ? 'none' : 'block'
}

假设HTML如:

<ul>
    <li><div onClick="furtherInfo(this);">Info one</div>
      <div id="test">Text for first info</div>
    </li>
    <li><div onClick="furtherInfo(this);">Info two</div>
      <div>Text for second info</div>
    </li>
    <!-- and so on... -->
  </ul>

JS Fiddle demo

答案 2 :(得分:0)

这是一个无ID解决方案:

window.onload = function() {
    var elems = document.getElementsByTagName("li");
    for(var i = 0; i < elems.length; i++) {
        elems[i].onclick = toggle;
    }
};

function toggle() {
    var divs = this.getElementsByTagName("div");
    divs[1].style.display = ((divs[1].style.display == "block") ? "none" : "block");
}

要限制“getElementsByTagName”,我建议您提供外部容器(class="pro-further"一个ID,因此它看起来像<section id="pro-further-toggles">,因此您可以指定var elems = document.getElementById("pro-further-toggles").getElementsByTagName("li");