[英]Javascript show/hide based on option select
So I have a list of cars, each car comes from a certain country. 所以我有汽车清单,每辆车都来自某个国家。 Each item has a div with a class of that certain country. 每个项目都有一个带有该特定国家/地区类别的div。
How can I make it show and hide based on the selection like 如何根据选择将其显示和隐藏
All Country1 Country2 所有国家1国家2
So if I select country1 I only want to see country 1 and if I select all I want to see all countries 因此,如果我选择country1我只想看国家1,如果我选择全部我想看所有国家
I have it working for 1 country, but when I press all nothing happens.. or when there is no div of the country then also nothing happens! 我有它在1个国家/地区工作,但是当我按所有按钮时,什么也没有发生。
<script>
function selectCountry() {
var country = document.getElementById("countryList");
display(country);
}
function display(value) {
var country = value;
var list = document.getElementsByClassName(country);
for (var i = 0; i < list.length; i++) {
list[i].style.display = 'block';
}
}
</script>
<form>
Select country:
<select id="countryList" onchange="selectCountry()">
<option value="all">All</option>
<?php foreach ($countries as $country) {
echo "<option value=" . $country. ">" . $country . "</option>";
} ?>
</select>
</form>
You should add all
class to every item. 您应该将all
类添加到每个项目。 Basically, when you select all
, you are doing this: 基本上,当您选择all
,您将执行以下操作:
function display(value) {
//VALUE == "all"
var country = value;
//GET EVERY ELEMENT WITH "all" CLASS
var list = document.getElementsByClassName(country);
//IN YOUR CASE "list.length == 0" SO NO HIGHLIGHT
for (var i = 0; i < list.length; i++) {
list[i].style.display = 'block';
}
}
You should post the divs code too to understand better the situation. 您也应该发布divs代码以更好地了解情况。
EDIT: 编辑:
In addition to what I wrote if you want to hide all element your display
function should be something like: 除了我写的要隐藏所有元素的display
功能外, display
功能还应类似于:
var allItems = document.getElementsByClassName("all");
for (var i = 0; i < allItems.length; i++) {
allItems[i].style.display = 'none';
}
var list = document.getElementsByClassName(country);
for (var i = 0; i < list.length; i++) {
list[i].style.display = 'block';
}
Not tested but should work. 未经测试,但应该可以。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.