多个切换链接

时间:2016-08-16 20:51:44

标签: javascript html

我正在使用HTML和JavaScript,我需要制作两个切换链接的实例。这是我的单个代码:

<script language="javascript"> 
function toggle() {
    var ele = document.getElementById("toggleText");
    var text = document.getElementById("displayText");
    if(ele.style.display == "block") {
            ele.style.display = "none";
        text.innerHTML = "link1";
    }
    else {
        ele.style.display = "block";
        text.innerHTML = "link1";
    }
} 
</script> 


<body> <a id="displayText" href="javascript:toggle()" style="font-size:160%;">link1</a> 
    <div id="toggleText" style="display: none; font-size:160%;"><p>paragraph1</p></div><br></body>

我需要两个切换链接,以便在单击每个文本时独立显示/隐藏不同的文本段落。如何在第一个实例下添加第二个实例?

1 个答案:

答案 0 :(得分:2)

为每个链接添加事件处理程序和data-toggle-id属性。在事件处理程序中,获取data-toggle-id的值,并使用它来查找要显示的段落。然后使用元素的classList的toggle方法添加/删除显示段落的类。

&#13;
&#13;
var links = document.querySelectorAll('[data-toggle-id]');

for (var ix = 0; ix < links.length; ix++) {
  links.item(ix).addEventListener('click', function() {
    document.getElementById(this.dataset.toggleId).classList.toggle('show');
  });
}
&#13;
.toggleText {
    display: none;
}

.show {
    display: block;
}
&#13;
<link href="//cdnjs.cloudflare.com/ajax/libs/skeleton/2.0.4/skeleton.min.css" rel="stylesheet" />
<div class="container">
  <a data-toggle-id="paragraph1">link1</a>
  <div class="toggleText" id="paragraph1">
    <p>paragraph1</p>
  </div>
</div>
<div class="container">
  <a data-toggle-id="paragraph2">link2</a>
  <div class="toggleText" id="paragraph2">
    <p>paragraph2</p>
  </div>
</div>
<div class="container">
  <a data-toggle-id="paragraph3">link3</a>
  <div class="toggleText" id="paragraph3">
    <p>paragraph3</p>
  </div>
</div>
&#13;
&#13;
&#13;

如果您讨厌循环,可以使用Nick的建议并将NodeList转换为数组并使用forEach方法:

Array.prototype.slice.call(document.querySelectorAll('[data-toggle-id]')).forEach(function(element) {
    element.addEventListener('click', function(){
        document.getElementById(this.dataset.toggleId).classList.toggle('show');
    });
});