You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

jQuery下拉框控制DIV显示:页面加载默认展示首个DIV

Solution for Your Dropdown and Display Requirements

Hey there! Let's fix up your dropdown and display behavior exactly how you want it. Here's a step-by-step solution with modified code:

1. Make State 1 & State 2 Non-Selectable Labels

Instead of using regular <option> elements for State 1 and State 2, we'll use <optgroup> tags—these are built specifically for grouping options and can't be selected by users, which fits your "only label" requirement perfectly.

2. Default Display & Toggle Logic

We'll add code to show the "All Locations" div on page load, then hide it when any other option is selected (while showing the corresponding location div).

Full Modified Code

<!-- HTML -->
<select id="locationSelector">
  <option value="all">All Locations</option>
  <optgroup label="State 1">
    <option value="loc1">Location 1</option>
    <option value="loc2">Location 2</option>
  </optgroup>
  <optgroup label="State 2">
    <option value="loc3">Location 3</option>
    <option value="loc4">Location 4</option>
  </optgroup>
</select>

<div id="allLocations" class="locationDiv">This is the All Locations content</div>
<div id="loc1" class="locationDiv" style="display:none;">Location 1 content</div>
<div id="loc2" class="locationDiv" style="display:none;">Location 2 content</div>
<div id="loc3" class="locationDiv" style="display:none;">Location 3 content</div>
<div id="loc4" class="locationDiv" style="display:none;">Location 4 content</div>
// jQuery
$(document).ready(function() {
  // Show All Locations div by default on page load
  $('#allLocations').show();

  $('#locationSelector').on('change', function() {
    const selectedValue = $(this).val();
    
    // Hide all location divs first
    $('.locationDiv').hide();
    
    if (selectedValue === 'all') {
      // Show All Locations if selected
      $('#allLocations').show();
    } else {
      // Show the selected location div, hide All Locations
      $('#' + selectedValue).show();
    }
  });
});

Key Explanations:

  • <optgroup>: This element creates a non-selectable header for your state groups. Users can click it to expand/collapse (depending on browser) but can't select it as an option, so it won't change the selected value.
  • Default Display: The $(document).ready() block ensures the "All Locations" div is visible as soon as the page loads.
  • Change Handler: We first hide all divs, then either show "All Locations" or the selected specific location div based on the dropdown value.

This should solve both of your issues cleanly!

内容的提问来源于stack exchange,提问作者Zedwinski

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:33:11