阅读选项属性

Reading option attribute

我有一个 select(转换成 select2)定义如下:

<select class="form-control" name="Questions[3].ANSWER_LOOKUP_OPTION_ID" id="Questions[3].ANSWER_LOOKUP_OPTION_ID" multiple="">
    <option value="57" data-index="1">Child Find/Public Awareness</option>
    <option value="58" data-index="2">Referral</option>
    <option value="59" data-index="3">Assessment/Evaluation</option>
    <option value="60" data-index="4">IFSP Development</option>
    <option value="61" data-index="5">Assistive Technology Services and Devices</option>
    <option value="62" data-index="6">Audiology</option>
    <option value="63" data-index="7">Auditory Services</option>
    <option value="64" data-index="8">Specialized skills training</option>
    <option value="65" data-index="9">Family Counseling</option>
</select>

使用此代码,我想将 $optionscsv 文本设置为所有 selected 选项的数据索引的值,而不是它们的 val();

var $options = $('#Questions\[3\]\.ANSWER_LOOKUP_OPTION_ID'),
    $optionscsv = $('span#optionscsv');
$("#Questions\[3\]\.ANSWER_LOOKUP_OPTION_ID")
    .select2()
    .on('change', function () {
        $optionscsv.text($options.val());
    });

当 Child Find/Public Awareness + Assessment/Evaluation + IFSP Development selected 时,上面代码的结果显示:57, 59, 60 期望的结果是:1, 3, 4

答案如下:

.on('change', function () {
    var selected_options = [];
    $(this).find("option:selected").each(function(){
        selected_options.push(parseInt($(this).attr('data-index')));
    });
    $optionscsv.text(selected_options.join());
});