Javascript 如何在 jQuery 中获得 $(this) 选择的选项?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10011802/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get $(this) selected option in jQuery?
提问by B Seven
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***
?
回答by jorgebg
For the selected value: $(this).val()
对于选定的值: $(this).val()
If you need the selected option element, $("option:selected", this)
如果您需要选定的选项元素, $("option:selected", this)
回答by user56reinstatemonica8
$(this).find('option:selected').text();
回答by angelmedia
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:
获取 value 属性:
$('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();
});
回答by user2053983
var cur_value = $('option:selected',this).text();
回答by He Shiming
This should work:
这应该有效:
$(this).find('option:selected').text();
回答by Platinum Azure
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 对象指向的节点的后代的选定选项:
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();
回答by thomthom
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();
回答by Likwid_T
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 树向下走一个分支......