如何使用jquery定位下拉选择器

时间:2017-11-03 11:56:55

标签: javascript jquery html

我在从下拉选择器中选择一个选项时尝试显示和隐藏div。

Div 1(第1季)应显示负载,Div 2(第2季)应隐藏。

当你通过下拉菜单选择Div 2(第2季)时,Div 1(第1季)应该隐藏,div 2(第1季)应该显示,反之亦然。

这是我的HTML -

 <h4>Season:</h4> 
    <select>
      <option value="s1">Winter 2017</option>
      <option value="s2">Summer 2017</option>
  </select>
<div id="season1">
    <table class="table table-hover table-striped">
        <thead>
  <tr>
    <th>Name</th>
    <th>GP</th> 
    <th>G</th>
    <th>A</th>
    <th>Pnts</th>
    <th>PiM</th>
  </tr>
</thead>
  <tr>
    <td>Adam</td>
    <td>12</td> 
    <td>2</td>
    <td>0</td>
    <td>2</td>
    <td>2</td>
  </tr>
</table>
</div>
<div id="season2">
    <table class="table table-hover table-striped">
        <thead>
  <tr>
    <th>Name</th>
    <th>GP</th> 
    <th>G</th>
    <th>A</th>
    <th>Pnts</th>
    <th>PiM</th>
  </tr>
</thead>
  <tr>
    <td>Brad</td>
    <td>15</td> 
    <td>5</td>
    <td>3</td>
    <td>6</td>
    <td>9</td>
  </tr>
</table>
</div>

JS

$(document).ready(function () {
                $('#season1').show();
                $('#season2').hide();


                $('#s1').prop('selected', true(e) {
                    $('#season1').show();
                    $('#season2').hide();
                });

                $('#s2').prop('selected', true(e) {
                    $('#season1').hide();
                    $('#season2').show();
                });


            });

http://jsfiddle.net/p40139bd/

1 个答案:

答案 0 :(得分:1)

我已将s1s2更改为season1season2,因此它们与div的ID相匹配

然后你可以使用:

$("select").on("change", function() {
  $('[id^=season]').hide();  // This will hide all element that has an id starting with season
  $('#' + $(this).val()).show();  // example '#season1'
})

<强>演示

&#13;
&#13;
$(document).ready(function() {
  $('#season1').show();
  $('#season2').hide();

  $("select").on("change", function() {
    $('[id^=season]').hide();
    $('#' + $(this).val()).show();
  })
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h4>Season:</h4>
<select>
  <option value="season1">Winter 2017</option>
  <option value="season2">Summer 2017</option>
</select>
<div id="season2">
  <table class="table table-hover table-striped">
    <thead>
      <tr>
        <th>Name</th>
        <th>GP</th>
        <th>G</th>
        <th>A</th>
        <th>Pnts</th>
        <th>PiM</th>
      </tr>
    </thead>
    <tr>
      <td>Adam</td>
      <td>12</td>
      <td>2</td>
      <td>0</td>
      <td>2</td>
      <td>2</td>
    </tr>
  </table>
</div>
<div id="season1">
  <table class="table table-hover table-striped">
    <thead>
      <tr>
        <th>Name</th>
        <th>GP</th>
        <th>G</th>
        <th>A</th>
        <th>Pnts</th>
        <th>PiM</th>
      </tr>
    </thead>
    <tr>
      <td>Brad</td>
      <td>15</td>
      <td>5</td>
      <td>3</td>
      <td>6</td>
      <td>9</td>
    </tr>
  </table>
</div>
&#13;
&#13;
&#13;