如何将列表项连接到div元素javascript

时间:2017-04-23 20:14:41

标签: javascript

我正在尝试构建一个垂直标签,但列表项应单独连接到div。所有的div都隐藏着display:none;当有人点击例如tab2时,第二个div应该变成display:block。换句话说,className"选择"将添加到该特定div。在console.log中出现以下错误(无法在HTMLUListElement中读取属性' classList' of null。)。这里的任何人都知道如何编写JavaScript,以便列表项连接到div。

请仅使用纯JavaScript。



document.getElementById("verticalUl").addEventListener("click", function(e) {
    var e = e || window.event,
		elements = document.getElementById("verticalUl").children, 
		content = document.querySelectorAll(".support-box");

    if(e.target && e.target.nodeName == "LI") { 
    	var attribute = e.target.getAttribute("id");
        for(var i = 0; i < elements.length; i++) {
            elements[i].classList.remove("active-support");
            
        }
        for (var i = 0; i < content.length; i++) {
            	content[i].classList.remove("selected");
            };
        document.querySelector("." + attribute + "-box").classList.add("selected");
        e.target.classList.add("active-support");
    }
});
&#13;
.group {
  display: none;
}

.selected {
  display: block;
}
.vertical-navbar {
  float: left;
  width: 20%;
}

.vertical-navbar li {
  list-style-type: none;
  border: 1px solid red;
  margin: 5px;
}

.support-box {
  width: 60%;
  float: right;
  height: 300px;
  border: 1px solid red;
}
&#13;
<ul class="vertical-navbar" id="verticalUl">
    <li id="tab1" class="support-tabs-label active-support">Hot Topics</li>

    <li id="tab2" class="support-tabs-label">Account</li>

    <li id="tab3" class="support-tabs-label">Product</li>

    <li id="tab4" class="support-tabs-label">Order and Shipping</li>
</ul>
            
<div class="content-support1  support-box tab1-box group selected">
Hot Topics
</div>

<div class="content-support2 support-box tab2-box group">
Account
</div>

<div class="content-support3 support-box tab3-box group">
Product
</div>

<div class="content-support4 support-box tab4-box group">
Order and Shipping
</div>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

假设所有{% for announcement in announcements %} <tr> <td>{{ forloop.revcounter }}</td> <td>{{ announcement.title }}</td> <td>{{ announcement.user.profile.name }}</td> <td>{{ announcement.modified }}</td> </tr> {% endfor %} 元素都有support-box,其中tabx-box与点击的tabx元素匹配,您只需使用:

li

解决方案

document.querySelector("." + attribute + "-box").classList.add("selected");

Django template "for" documentation