如何在jQuery中获得$(this)选择的选项?

B S*_*ven 82 javascript jquery

以下代码有效:

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

如何重构第二行:

var cur_value = $(this).***option-selected***.text();
Run Code Online (Sandbox Code Playgroud)

你用的是***option-selected***什么?

jor*_*ebg 109

对于选定的值: $(this).val()

如果您需要选定的选项元素, $("option:selected", this)


use*_*ca8 94

 $(this).find('option:selected').text();
Run Code Online (Sandbox Code Playgroud)


小智 52

我认为最佳和最短的方式是在下拉列表上的onchange事件中获取所选的选项:

$('option:selected',this);
Run Code Online (Sandbox Code Playgroud)

获取value属性:

$('option:selected',this).attr('value');
Run Code Online (Sandbox Code Playgroud)

获取标签之间显示的部分:

$('option:selected',this).text();
Run Code Online (Sandbox Code Playgroud)

在你的样本中:

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


小智 35

var cur_value = $('option:selected',this).text();
Run Code Online (Sandbox Code Playgroud)


He *_*ing 10

这应该工作:

$(this).find('option:selected').text();
Run Code Online (Sandbox Code Playgroud)


Pla*_*ure 8

您可以使用find查找选定的选项,该选项是当前jQuery对象指向的节点的后代:

var cur_value = $(this).find('option:selected').text();
Run Code Online (Sandbox Code Playgroud)

由于这可能是一个直接的孩子,我实际上建议使用.children:

var cur_value = $(this).children('option:selected').text();
Run Code Online (Sandbox Code Playgroud)


tho*_*hom 7

var cur_value = $(this).find('option:selected').text();
Run Code Online (Sandbox Code Playgroud)

既然option很可能是select你的直接孩子也可以使用:

var cur_value = $(this).children('option:selected').text();
Run Code Online (Sandbox Code Playgroud)

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