【问题标题】:jQuery select2 - how to get property from option?jQuery select2 - 如何从选项中获取属性?
【发布时间】:2014-07-26 13:36:40
【问题描述】:

如何使用 bootstrap 中的 select2 从 SELECT 内的 selected(!) OPTION 元素中获取属性?

HTML:

<select id="select_project_type">
    <option value="1" required-property="A">Option 1</option>
    <option value="2" required-property="B">Option 2</option>
</select>

JS:

$('#select_project_type').select2({
    placeholder: $('#select_project_type').prop('placeholder')
});

$('#select_project_type').on('select2-selecting', function(e) {
    console.log(e); // Here I got all object, but I don't know how 
                    // to get required-property from selected option
});

【问题讨论】:

    标签: jquery twitter-bootstrap jquery-select2


    【解决方案1】:

    我们可以将属性更新为 data-required-property ,

    然后你可以试试下面的代码:

    $('.select2').select2({
    placeholder: $('.select2').prop('placeholder')
    });
    
    $('#select_project_type').on('select2-selecting', function(e) {
       console.log($(this).find(":selected").data('required-property')); 
    });
    

    DEMO

    【讨论】:

      【解决方案2】:

      您可以尝试像这样使用精确的 CSS 选择器:

      $("#select_project_type option[value=1]").attr("required-property");
      $("#select_project_type option[value=2]").attr("required-property")
      

      演示:http://jsfiddle.net/2cXt5/

      编辑:要仅从所选选项中获取属性,请使用此选择器:

      $("#select_project_type option:selected").attr("required-property");
      

      另外,您可能希望使用 select change event 来查找选项何时更改并更新 ypur 数据。

      演示:http://jsfiddle.net/2cXt5/2/

      【讨论】:

      • 是的,但我只需要所选选项的必需属性。
      • @ZaquPL 哦,我的错,等一下,我会解决这个问题
      • @ZaquPL 已编辑,请告诉我它是否不是您真正想要的
      猜你喜欢
      • 1970-01-01
      • 2013-10-09
      • 1970-01-01
      • 1970-01-01
      • 2014-02-06
      • 2013-12-17
      • 1970-01-01
      • 2019-12-23
      • 1970-01-01
      相关资源
      最近更新 更多