在加载和单击时检查下拉列表的值

check value of drop-down list at load and on click

本文关键字:下拉列表 检查 加载 单击      更新时间:2023-09-26

我有一个下拉列表,我需要捕获页面加载时间和更改时的值。如果未选择报告字段,则不显示状态列表或年份列表,如果选择了报告字段(无论是在加载时还是当用户从下拉列表中选择它时),则显示相应的div。

任何帮助不胜感激,谢谢。

<script type="text/javascript"> 
$(document).ready(function() {
 checkReport();
});
</script>
<select name="report" id="report">
<option></option>
<option value="state">State</option>
<option value="year">Year</option>
</select>
<div id="state-list">NY, CA, TX</div>
<div id="year-list">2012, 2013, 2014</div>
function checkReport() {
  $('#report').live('change', function() {
    $('#year-list, #state-list).hide();
    var report = $('#report').val();
    if (report) {
      $('#' + type_of_report + '-list').show();
    } else {
      $('#year-list, #state-list).hide();
    }
  });
}
$(document).ready(function() {
checkReport();
 $('#report').live('change', checkReport);
});
function checkReport() {
    var report = $('#report').val();
    $('#year-list, #state-list').hide();
    if (report) {
      $('#' + report + '-list').show();
    }
}

我想这就是你需要的

尝试:

<select name="report" id="report">
    <option value="">Select a type of report</option>
    <option value="state">State</option>
    <option value="year">Year</option>
</select>
<div id="state-list">NY, CA, TX</div>
<div id="year-list">2012, 2013, 2014</div>
<script type="text/javascript"> 
$(function(){
    checkReport($('#report')[0]);
    $('#report').on('change', function() {
        checkReport(this);
    });
    function checkReport(r) {            
        $('#year-list,#state-list').hide().filter(function(){
            return r.value.length > 0 &&   
             $(this).is('#' + r.value + '-list')
        }).show();            
    }
});
</script>

证明:http://jsfiddle.net/iambriansreed/qvq3z/

笔记:

  1. 我用说明替换了空白选项。

  2. 您不需要$('#report').on('change',因为select最初是 DOM 的一部分。无需实时捕获。你可以做:$('#report').change(。我添加它只是为了保持您的问题中显示的live功能。