简体   繁体   English

如何在 jQuery 中获取 $(this) selected 选项?

[英]How to get $(this) selected option in jQuery?

The following code works:以下代码有效:

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

How to refactor the second line to:如何将第二行重构为:

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

What do you use for ***option-selected*** ?你用***option-selected***做什么?

For the selected value: $(this).val()对于选定的值: $(this).val()

If you need the selected option element, $("option:selected", this)如果需要选中的option元素, $("option:selected", this)

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

Best and shortest way in my opinion for onchange events on the dropdown to get the selected option:在我看来,下拉列表中的 onchange 事件获取所选选项的最佳和最短方法:

$('option:selected',this);

to get the value attribute:获取值属性:

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

to get the shown part between the tags:获取标签之间的显示部分:

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

In your sample:在你的样本中:

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

This should work:这应该工作:

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

You can use find to look for the selected option that is a descendant of the node(s) pointed to by the current jQuery object:您可以使用find查找所选选项,该选项是当前 jQuery object 指向的节点的后代:

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

Since this is likely an immediate child, I would actually suggest using .children instead:由于这可能是直系子代,因此我实际上建议改用.children

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

Since option is likely to be immediate child of select you can also use:由于option很可能是select的直接子项,您还可以使用:

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

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

Best guess:最佳的揣测:

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

I like children better in this case because you know you're only going one branch down the DOM tree...在这种情况下,我更喜欢孩子,因为你知道你只会沿着 DOM 树向下移动一个分支......

It's just只是

$(this).val();

I think jQuery is clever enough to know what you need我认为 jQuery 足够聪明,知道你需要什么

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM