代码之家  ›  专栏  ›  技术社区  ›  Jack

从动态选择选项获取文本

  •  1
  • Jack  · 技术社区  · 10 年前

    我有多个选择选项,我想写文本 car 或 motorcycle 在…上 .texts

    这是几个动态选择选项

    <td>
    
    <select id="area-0">
      <option value="1">Car</option>
      <option value="2">Motorcycle</option>
    </select>
    </td>
    
    <td class="texts"></td>
    
    <td>
        <select id="area-1">
          <option value="1">Car</option>
          <option value="2">Motorcycle</option>
        </select>
    </td>
    
    <td class="texts"></td>
    

    这是我的剧本

    $('select[id^=area]').change(function(){
        var text_t = $(this option:selected).text();
      $(this).parent().next().html(text_t);
    
    });
    

    我该如何放置 汽车 或 摩托车 在…上 .文本

    2 回复  |  直到 10 年前
        1
  •  1
  •   Rayon    10 年前

    您有无效的 html .把它包起来 table -> tr

    $(this option:selected) 不是有效的选择器。使用 $(this).find('option:selected')

    $('select[id^=area]').change(function() {
      var text_t = $(this).find('option:selected').text();
      $(this).parent().next().html(text_t);
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
    <table>
      <tr>
        <td>
          <select id="area-0">
            <option value="1">Car</option>
            <option value="2">Motorcycle</option>
          </select>
        </td>
        <td class="texts"></td>
        <td>
          <select id="area-1">
            <option value="1">Car</option>
            <option value="2">Motorcycle</option>
          </select>
        </td>
        <td class="texts"></td>
      </tr>
    </table>
        2
  •  0
  •   Satpal    10 年前

    您可以使用 .find() 方法获取选定的 option 的文本。根据当前的实现,您必须得到语法错误。

    var text_t = $(this).find('option:selected').text();
    

    而不是

    var text_t = $(this option:selected).text();