jQuery에서 $ (this) 선택한 옵션을 얻는 방법은 무엇입니까?


91

다음 코드가 작동합니다.

$("#select-id").change(function(){
  var cur_value = $('#select-id option:selected').text();
  . . .
});

두 번째 줄을 다음과 같이 리팩터링하는 방법 :

var cur_value = $(this).***option-selected***.text();

무엇을 위해 사용 ***option-selected***합니까?

답변:


120

선택한 값 : $(this).val()

선택한 옵션 요소가 필요한 경우 $("option:selected", this)


101
 $(this).find('option:selected').text();

이것은 나를 위해 완벽하게 작동했습니다 $("option:selected", this). 위에서 언급 한대로 시도했지만 문제가있었습니다. 버튼 클릭을 사용하여 선택한 옵션 요소 텍스트를 다른 div에 추가했지만 버튼을 클릭했을 때 실제로 선택한 요소가 변경되었습니다 ... 이상합니다. 이것을 사용하십시오.
skwidbreth

53

드롭 다운에서 onchange 이벤트를 선택하여 선택한 옵션을 얻을 수있는 가장 좋고 가장 짧은 방법은 다음과 같습니다.

$('option:selected',this);

값 속성을 얻으려면 :

$('option:selected',this).attr('value');

태그 사이에 표시된 부분을 얻으려면 :

$('option:selected',this).text();

샘플에서 :

$("#select-id").change(function(){
  var cur_value = $('option:selected',this).text();
});

를 사용하지 마십시오. .contextjQuery 1.10부터 사용되지 않습니다.- api.jquery.com
category

네,하지만 당신 말은 이것이다 : api.jquery.com/context의 $ ( "UL"는 document.body) .context.nodeName 내가 사용하지는되는
angelmedia

1
나는 대답을 좋아하는데 왜 그것이 가장 좋은가?
Sébastien Gicquel



9

를 사용 find하여 현재 jQuery 객체가 가리키는 노드의 자손 인 선택된 옵션을 찾을 수 있습니다 .

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

이것은 직계 자식 일 가능성이 높으므로 실제로 .children대신 사용 하는 것이 좋습니다 .

var cur_value = $(this).children('option:selected').text();

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

option직계 자식이 될 가능성이 높기 때문에 select다음을 사용할 수도 있습니다.

var cur_value = $(this).children('option:selected').text();

http://api.jquery.com/find/


option-selected따옴표없이 어디에서 얻 습니까 ...?
플래티넘 푸른

제가 게시했을 때 오타였습니다. 답을 수정했습니다.
thomthom

find('option:selected')나를 위해 빈 문자열을 반환합니다. 어떤 버전의 jQuery가 필요합니까? 1.6.1에서 작업하고 있습니다. children('option:selected')작동합니다.
B Seven

option:selected버전 1.0부터있어왔다 api.jquery.com/selected-selector
thomthom

0

최선의 추측:

var cur_value = $('#select-id').children('option:selected').text();

나는이 경우에 아이들이 더 좋아진다. 왜냐하면 당신이 DOM 트리 아래로 한 가지만 가고 있다는 것을 알고 있기 때문이다.


아마도 당신이 정말로 의미했던 것은 var cur_value = $ (this) .children ( 'option : selected'). text ();
Joe Johnston

0

그냥

$(this).val();

나는 jQuery가 당신이 필요한 것을 알만큼 충분히 영리하다고 생각합니다.

당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.