【问题标题】:JavaScript show and hide select listJavaScript 显示和隐藏选择列表
【发布时间】:2018-01-08 03:09:55
【问题描述】:

我有一个选择列表,其中包含例如国家/地区:

<select id="Countries" name="Countries" onChange="check();">
   <option id="Countrie1" name="Countrie1">Country 1</option>
   <option id="Countrie2" name="Countrie2">Country 2</option>
</select>

我想使用 Javascript 来隐藏和显示另一个选择列表(团队列表),具体取决于国家选择列表的选定元素。

例如,如果选择了国家 1,则显示球队的国家 1 选择列表

<select id="Teams_Country_1" name="Teams_Country_1">
   <option id="C1_Team1" name="C1_Team1">Team_1_Country_1</option>
   <option id="C1_Team2" name="C1_Team2">Team_2_Country_1</option>
</select> 

如果选择了 Country 2,则隐藏第一个并在相同位置显示第二个。

<select id="Countries" name="Countries">
   <option id="C2_Team1" name="C2_Team1">Team_1_Country_2</option>
   <option id="C2_Team2" name="C2_Team2">Team_2_Country_2/option>
</select>

这是我正在尝试修改以使其工作的代码。

function check() {
    var el = document.getElementById("Countries");
    var str = el.options[el.selectedIndex].text;
    if (str == "Countrie1") {
        showTeamsC1();
        hideTeamsC2();
    } else if (str == "Countrie2") {
        showTeamsC2();
        hideTeamsC1();
    }
}
function hideTeamsC1() {
    document.getElementById('Teams_Country_1').style.visibility = 'hidden';
}
function showTeamsC1() {
    document.getElementById('Teams_Country_1').style.visibility = 'visible';
}
function hideTeamsC2() {
    document.getElementById('Teams_Country_2').style.visibility = 'hidden';
}
function showTeamsC2() {
    document.getElementById('Teams_Country_2').style.visibility = 'visible';
}

但这不会在同一位置显示选择列表,如果我手动执行(尝试使用 margin-top)它会覆盖另一个列表。

【问题讨论】:

  • 你试过用显示代替可见性吗?
  • 最后一个选择应该命名为“Teams_Country_2”。此外,在其选项“C2_Team2”中,您错过了打开结束标签。也可以使用值,而不是标签。例如,将属性“值”添加到所有“选项”标签中,并且不要在其中使用空格。然后像这样定义“str”:var str = el.options[el.selectedIndex].value;。并使用“===”运算符。并开始使用 jQuery。祝你好运。
  • 好的,谢谢

标签: javascript html


【解决方案1】:

您需要使用display: none; 而不是visibility:hidden; What is the difference between visibility:hidden and display:none?

可见性隐藏是隐藏元素但保留其空间,但display:none; 隐藏它而不保留其空间。

所以你的代码会是这样的:

function hideTeamsC1() {
    document.getElementById('Teams_Country_1').style.display = 'none';
}
function showTeamsC1() {
    document.getElementById('Teams_Country_1').style.display = 'block';
}
function hideTeamsC2() {
    document.getElementById('Teams_Country_2').style.display = 'none';
}
function showTeamsC2() {
    document.getElementById('Teams_Country_2').style.display = 'block';
}

【讨论】:

  • 然后如果我想显示它。我需要用什么?
  • 显示:内联;或显示:阻止;
猜你喜欢
  • 2014-11-23
  • 2023-03-12
  • 1970-01-01
  • 1970-01-01
  • 2023-01-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-10
相关资源
最近更新 更多