我正在为我的select标签使用onchange函数,以根据select选项值过滤项目列表。
我目前拥有的代码仅适用于单个选择标签,但我希望它能够适用于多个选择标签,这将需要每个选择选项值进行配合。
例如,如果我具有“部门”和“位置”作为列表中每个项目的标签,并且在选择标签中选择“部门”->“ IT和位置”->“纽约”,则我只想查看“部门”和“位置”中的IT部门列表。纽约。
我很难理解如何正确执行此操作。我假设某种for循环可获取每个选择标记,然后在每个选择标记中获取当前选项的值,并且仅在满足选择选项值标准的情况下显示列表项。
我将不胜感激如何实现这一目标!
HTML:
<select class="filterTags" id="filterDepartment">
<option>All</option>
<option>IT</option>
<option>Marketing</option>
</select>
<select class="filterTags" id="filterLocation">
<option>All</option>
<option>New York</option>
<option>Washington</option>
</select>
<div class="tags-container">
<div class="tags tags-departments">
<span class="department tag">IT</span>
<span class="department tag">Marketing</span>
</div>
<div class="tags tags-locations">
<span class="location tag">New York</span>
<span class="location tag">Washington</span>
</div>
</div>
JavaScript:
var selectClass = document.getElementsByClassName("filterTags")
selectClass = selectClass[0]
selectClass.onchange= function() {
var filterOptions, tags, i, span;
filterOptions = this.options[this.selectedIndex].value
tags = document.getElementsByClassName("tags-departments")
span = document.querySelectorAll(".department")
for (i = 0; i < tags.length; i++) {
if (span) {
if (span[i].innerHTML.indexOf(filterOptions) > -1) {
span[i].parentNode.parentNode.parentNode.style.display = ""
} else {
span[i].parentNode.parentNode.parentNode.style.display = "none"
}
if(filterOptions == "All") {
span[i].parentNode.parentNode.parentNode.style.display = ""
}
}
}
}
好吧,我建议以下逻辑,将一个功能添加到onchange
两个选择元素的事件中,该功能将:
这是一个完全有效的代码和一个有效的示例:
//Iterate the selection elements and add the function to the 'change' event
sels = document.getElementsByTagName('select');
for(i=0; i<sels.length; i++)
{
sels[i].addEventListener('change', function() {
//get the selection id of the selected that was change - this returns the selection element
selectionID = this.id;
if(selectionID === "filterDepartment")
{
//the value of the selected department
var selectedDepartment = document.getElementById("filterDepartment").value
//we will iterate the departments spans and check their text value agains the selected department value (or if the value is 'All' we dont need to check//
var spans = document.getElementsByClassName('tags tags-departments')[0].getElementsByTagName('span');
for(var i = 0; i < spans.length; i++)
{
if(selectedDepartment == "All" || spans[i].innerText == selectedDepartment)
{
spans[i].style.display = "block";
}
else
{
spans[i].style.display = "none";
}
}
}
if(selectionID === "filterLocation")
{
var selectedLocation = document.getElementById("filterLocation").value;
var spans = document.getElementsByClassName('tags tags-locations')[0].getElementsByTagName('span');
for(var i = 0; i < spans.length; i++)
{
if(selectedLocation == "All" || spans[i].innerText == selectedLocation)
{
spans[i].style.display = "block";
}
else
{
spans[i].style.display = "none";
}
}
}
}, false);}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句