[jquery] 선택 변경시 데이터 속성 값 가져 오기

다음 코드는 ‘undefined’를 반환합니다.

$('select').change(function(){
    alert($(this).data('id'));
});

<select>
    <option data-id="1">one</option>
    <option data-id="2">two</option>
    <option data-id="3">three</option>
</select>



답변

선택한 옵션을 찾아야합니다.

$(this).find(':selected').data('id')

또는

$(this).find(':selected').attr('data-id')

첫 번째 방법이 바람직하지만.


답변

다음을 시도하십시오 :

$('select').change(function(){
  alert($(this).children('option:selected').data('id'));
});

변경 가입자는 select의 change 이벤트를 구독하므로 this매개 변수는 select 요소입니다. data-id를 가져 오려면 선택한 자식을 찾아야합니다.


답변

document.querySelector('select').onchange = function(){
   alert(this.selectedOptions[0].getAttribute('data-attr'));
};


답변

바닐라 자바 ​​스크립트 :

this.querySelector(':checked').getAttribute('data-id')


답변

당신은 사용할 수 있습니다 context와 구문을 this하거나 $(this). 이것은와 같은 효과 find()입니다.

$('select').change(function() {
    console.log('Clicked option value => ' + $(this).val());
    <!-- undefined console.log('$(this) without explicit :select => ' + $(this).data('id')); -->
    <!-- error console.log('this without explicit :select => ' + this.data('id')); -->
    console.log(':select & $(this) =>    ' + $(':selected', $(this)).data('id'));
    console.log(':select & this =>       ' + $(':selected', this).data('id'));
    console.log('option:select & this => ' + $('option:selected', this).data('id'));
    console.log('$(this) & find =>       ' + $(this).find(':selected').data('id'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select>
    <option data-id="1">one</option>
    <option data-id="2">two</option>
    <option data-id="3">three</option>
</select>

미세 최적화의 문제로을 선택할 수 있습니다 find(). 코드 골퍼가 더 많으면 컨텍스트 구문이 더 간단합니다. 기본적으로 코딩 스타일이 적용됩니다.

관련 성능 비교 는 다음과 같습니다 .


답변

$('#foo option:selected').data('id');


답변

이것은 나를 위해 작동

<select class="form-control" id="foo">
    <option value="first" data-id="1">first</option>
    <option value="second" data-id="2">second</option>
</select>

그리고 스크립트

$('#foo').on("change",function(){
    var dataid = $("#foo option:selected").attr('data-id');
    alert(dataid)
});