【问题标题】:jQuery - Get Select Value and Update Div With Multiple Select MenusjQuery - 使用多个选择菜单获取选择值并更新 div
【发布时间】:2015-07-07 22:17:56
【问题描述】:

jsFiddle:https://jsfiddle.net/x9bbb14n/

例如,我有以下 HTML:

<select name="sweets">
  <option>Chocolate</option>
  <option selected="selected">Candy</option>
  <option>Taffy</option>
  <option>Caramel</option>
  <option>Fudge</option>
  <option>Cookie</option>
</select>
<div class="sweets"></div>

<select name="cars">
  <option>Ford</option>
  <option selected="selected">Jaguar</option>
</select>
<div class="cars"></div>

我有这个 jQuery

$( "select" ).change(function () {
    var str = "";
    str = $( "select option:selected" ).text();
    $( "div" ).text( str );
  })
  .change();

我知道这是不正确的,但我希望能够选择一个选项和 要更新的 DIV,然后转到另一个菜单,选择一个选项并让它更新 其 DIV

我遗漏了什么明显的东西?

谢谢

【问题讨论】:

    标签: jquery


    【解决方案1】:

    您可以使用当前单击的元素上下文以及下一个选择器来定位所需的 div:

    $( "select" ).change(function () {
      var str = $(this).find("option:selected" ).text();
      $(this).next().text( str );
    }).change();
    

    Working Demo

    【讨论】:

      【解决方案2】:

      使用 $(this) 获取 jquery 中的当前对象

      $("select").change(function () {
        var str = $("option:selected", this).text();
        $('.' + $(this).attr('name')).text(str);
      }).change();
      

      Fiddle

      【讨论】:

        【解决方案3】:
        $( "select" ).change(function () {
            var selectname = $(this).attr('name');
            var str = $(this).find("option:selected" ).text();
            $( "div."+selectname ).text( str );
          })
          .change();
        

        我发现这是最好的,因为 DIV 可以在页面上移动

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2023-03-08
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-05-25
          相关资源
          最近更新 更多