jquery find选择div中的选定选项
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10237897/
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
jquery find selects selected option within div
提问by chris
Trying to figure out how to get a selects selected option where there is no id or class to use as a selector, but is contained within a specific div (theres multiple selects on the page I only want this one).
试图弄清楚如何在没有 id 或 class 用作选择器但包含在特定 div 中的情况下获取 selects selected 选项(页面上有多个选择,我只想要这个)。
Not sure if I should do something with find, parent, sibling, other... Example of what I am working with.
不确定我是否应该对查找、父级、兄弟级、其他……我正在使用的示例做些什么。
<div id="mydiv">
<select name="myselect">
<option selected="selected" value="1">Hi</option>
</select>
</div>
采纳答案by Alp
You can use the >symbol to select direct children. :selectedreturns selected options.
您可以使用该>符号来选择直接子级。:selected返回选定的选项。
jQuery('#mydiv > select[name=myselect] > option:selected')
If you want all selected options use this:
如果您想要所有选定的选项,请使用以下命令:
jQuery('option:selected')
To get the selectelements of those selected options:
要获取select这些选定选项的元素:
jQuery('option:selected').parent();
回答by Jasper
You can select by name:
您可以按名称选择:
var val = $('select[name="myselect"]').val();
Here is a list of ways to select using jQuery (it's awesomely long): http://api.jquery.com/category/selectors/
以下是使用 jQuery 进行选择的方法列表(它非常长):http: //api.jquery.com/category/selectors/
Since it's a child element you can also do this:
因为它是一个子元素,你也可以这样做:
var val = $('#mydiv').children('select[name="myselect"]').val();
This starts with your DIV that has an ID, then gets the children of that element that are select element(s) with the nameattribute set to myselect.
这从具有 ID 的 DIV 开始,然后获取该元素的子元素,这些元素是name属性设置为 的select 元素myselect。
If your selectelement was not a direct descendant then you could use .find()instead:
如果您的select元素不是直接后代,那么您可以使用.find():
var val = $('#mydiv').find('select[name="myselect"]').val()
Docs for ya:
给你的文件:
.children(): http://api.jquery.com/children.find(): http://api.jquery.com/find.val(): http://api.jquery.com/val
.children():http: //api.jquery.com/children.find():http: //api.jquery.com/find.val():http: //api.jquery.com/val
Note that calling .val()in a selectelement will return the valueof the selected option.
请注意,调用.val()的select元素将返回value选定的option。
回答by Madbreaks
You can select it by name:
您可以按名称选择它:
var sel = $('select[name=myselect]');
Cheers
干杯
回答by Priyeshj
Try doing $('div#mydiv > select > option[selected="selected"]')
尝试做 $('div#mydiv > select > option[selected="selected"]')

