我正在尝试在“家庭”网站上制作一个“圣诞节清单”页面,我希望它有一个下拉列表,其中列出了每个有清单的人,当您单击某人的名字时,它会显示他们的清单。
我在考虑使用display:none和display:block的方法。
但是我不确定如何去做,我从来没有真正做过这样的事情。
如果有人发布解决方案,我希望它不是JQuery,因为我不太了解。但是,这只是一个偏爱,任何帮助将不胜感激。
最佳答案
您有正确的主意。有很多方法可以做到这一点,但是这是一种显示正确列表并隐藏所有其他列表的方法。
// Get references to the elements in question
var people = document.getElementById("people");
// Get all the lists in a collection and convert that collection to an Array
var allLists = Array.prototype.slice.call(document.querySelectorAll(".list"));
// Set up a change event handler on the drop down list
// so that when the selection in the drop down changes,
// the associated function will execute
people.addEventListener("change", function(){
// Store the currently selected person
var person = this.value;
// Loop through all the lists and show the matching one and hide all the others
allLists.forEach(function(list){
if(person === list.id){
list.classList.remove("hidden");
} else {
list.classList.add("hidden");
}
});
});
/* Set all lists to be hidden by default */
.hidden.list { display:none; }
<select id="people">
<option value="">--- Choose A Person ---</option>
<option value="tom">Tom</option>
<option value="mary">Mary</option>
<option value="sue">Sue</option>
</select>
<div id="tom" class="hidden list">
<h1>Tom's List</h1>
<ul>
<li>item</li>
<li>item</li>
<li>item</li>
</ul>
</div>
<div id="mary" class="hidden list">
<h1>Mary's List</h1>
<ul>
<li>item</li>
<li>item</li>
<li>item</li>
</ul>
</div>
<div id="sue" class="hidden list">
<h1>Sue's List</h1>
<ul>
<li>item</li>
<li>item</li>
<li>item</li>
</ul>
</div>