使用 javascript/ 显示和隐藏选择框

Showing and hiding select boxes using javascript/

本文关键字:隐藏 选择 显示 javascript 使用      更新时间:2023-09-26

我有一点测试代码,打算在选择某个选项时显示一个选择框,然后在该选项更改时隐藏。

.HTML:

<form>
    <select id="sel1" name="sel1" class="chzn-select">
        <option value="1">1</option>
        <option value="2">2</option>
        <option value="3">3</option>
    </select>
    <select id="sel2" name="sel2" selected="selected" style="display:none">
        <option value="1">1</option>
        <option value="2">2</option>
    </select>
</form>

.JS:

var selCategory = $('#sel1');
$(selCategory).change(function () {
  $('option:selected').each(function () {
    if ($(this).text() ==='2') {
      $('#sel2').show();
    }
    else if($(this).text() ==='1') {
      $('#sel2').hide();
    }
    else if($(this).text() ==='3') {
      $('#sel2').hide();
    }
  });
});

只有这样的话,这段代码效果很好:

if ($(this).text() ==='2') {
  $('#sel2').show();
}

是 JavaScript,但在添加 else if 语句时会下降。另外,显示选择框本身或包含div 标签会更好吗?第二个选择框不是选择的唯一原因是选择似乎不喜欢已经隐藏的元素(宽度问题)。

任何帮助将不胜感激。

您的$('option:selected')选择器正在查看所有select元素的选项,而不仅仅是#sel1 。所以显示#sel2(由于在#sel1中选择了"2"),然后立即隐藏(由于在#sel2本身选择了"1")。 确保只查看所需的值:

var selCategory = $('#sel1');
selCategory.change(function () {
  selCategory.find('option:selected').each(function () {
    if ($(this).text() =='2') {
      $('#sel2').show();
    }
    else {
      $('#sel2').hide();
    }
  });
});

我会让它更容易,抓住value并从中连接sel ID:

$("#sel1").change(function() {
    $("select:not(#sel1)").hide(); //hide other selects, excluding #sel1
    $("#sel" + this.value).show();
});