【问题标题】:jQuery - Display Opposite (Invert Selection) Value of Select DropdownjQuery - 显示选择下拉列表的相反(反转选择)值
【发布时间】:2015-02-18 02:15:22
【问题描述】:

我想显示选定下拉列表的相反值。

如果我从 Batting 下拉菜单中选择“Team A”,则保龄球队应该是“Team B,反之亦然。

HTML

Batting: 
<select class="battingTeam">
  <option>-- Select Team --</option>
  <option>Team A</option>
  <option>Team B</option>
</select>

<div id="bowlingTeam"></div>

jQuery

​​>
$(document).ready(function(){
    $(".battingTeam").change(function(){
        $("#bowlingTeam").html( 'Bowling:' + this.options[this.selectedIndex].textContent);
     });                      
});


FIDDLE

【问题讨论】:

标签: jquery selectedvalue


【解决方案1】:
$(document).ready(function(){
    $(".battingTeam").change(function(){
        var batTeam = $(this).val();
        var bowlTeam = ( batTeam == "Team B" )?"Team A":"Team B";
        $('#bowlingTeam').html("Bowling:" +bowlTeam );
    });
});

检查小提琴:http://jsfiddle.net/hoja/24427kda/1/

【讨论】:

    【解决方案2】:

    试试

    $(document).ready(function () {
        $(".battingTeam").change(function () {
            var value = (this.selectedIndex == 0) ? 0 : (this.selectedIndex == 1) ? 2 : 1;
            (value == 0) ? $("#bowlingTeam").hide() : $("#bowlingTeam").show().html('Bowling:' + this.options[value].textContent);
    
        });
    });
    

    DEMO

    【讨论】:

      【解决方案3】:

      teams的选项添加一个类,那么你不需要知道具体的值

      <option class="team">Team A</option>
      <option  class="team">Team B</option>
      

      JS

       $(".battingTeam").change(function () {       
          $("#bowlingTeam").html('Bowling:' + $(this).find('.team:not(:selected)').text());
      });
      

      DEMO

      【讨论】:

      • 如果我选择选项 0(选择团队),它将显示 2 个团队
      猜你喜欢
      • 2021-01-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多