【问题标题】:jQuery, class of selected item from selectboxjQuery,从选择框中选择的项目的类
【发布时间】:2014-06-13 17:29:08
【问题描述】:

我有以下html:

<div class="form-group select optional reservation_reception_location">
 <select class="select optional form-control" id="reservation_reception_location_id" name="reservation[reception_location_id]">
   <option value=""></option>
   <option class="Office" value="1">Oddział Częstochowa</option>
   <option class="Airport" value="2">dasdasd</option>
 </select>
</div>

现在我的目标是了解所选元素的类别。因此,当我选择第一个时,我会将其类分配给我的 coffescript 文件中的值。我尝试过这样的事情:

$('#reservation_reception_location_id').attr('class')

但这仅显示主要的 div 类。 如果有人可以帮助我,我将不胜感激。

【问题讨论】:

    标签: javascript jquery coffeescript


    【解决方案1】:
    $('#reservation_reception_location_id').change(function(){
      var selectedClass=$(this).find("option:selected").attr("class");
    });
    

    【讨论】:

      【解决方案2】:

      您可以使用 :selected 选择器来获取选中的选项:

      $('#reservation_reception_location_id option:selected').attr('class')
      

      如果您想在您的select 已更改时获得选定的选项,请使用 .change() 事件:

      $('#reservation_reception_location_id').change(function() {
          var cls = $(this).find('option:selected').attr('class');
          console.log(cls);    
      });
      

      Fiddle Demo

      【讨论】:

      • 这个方案更加优化了。
      • @Superdrac 更优化是什么意思?比较什么?
      • 到下面找到。
      • @Superdrac 所以这是错误的,.find() 性能更高,甚至可以以纳秒为单位计算差异
      • 好的,对不起 Wolff,感谢您的澄清!
      猜你喜欢
      • 1970-01-01
      • 2011-11-16
      • 1970-01-01
      • 1970-01-01
      • 2018-04-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-23
      相关资源
      最近更新 更多