Javascript 动态获取更改的选择值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3477920/
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
Dynamically get changed select value
提问by Scott
I need to get the value of the selected option (when changed) in a select list and change the text in a span next to the select list. The problem is I don't know the id of the select list. There are a lot of different select lists on the page (5-25+) and they are all created dynamically, and so I can't have the id specified in the .change(). Here is what I have:
我需要在选择列表中获取所选选项(更改时)的值,并在选择列表旁边的跨度中更改文本。问题是我不知道选择列表的 ID。页面上有很多不同的选择列表(5-25+),它们都是动态创建的,所以我不能在.change(). 这是我所拥有的:
JavaScript:
JavaScript:
$("select").change(function () {
var str = "";
str = $("select option:selected").text();
$(".out").text(str);
}).trigger('change');
(Of course this doesn't work, puts all of the select values in each span.)
(当然这不起作用,将所有选择值放在每个跨度中。)
HTML:
HTML:
<select name="animal[]">
<option value="dog">dog</option>
<option value="cat">cat</option>
<option value="bird">bird</option>
<option value="snake">snake</option>
</select>
<span class="out"></span>
What am I missing?
我错过了什么?
回答by Ken Redler
Try something like this:
尝试这样的事情:
$("select").change(function () {
var txt = $(this).val();
$(this).next('span.out').text(txt);
}).trigger('change');?
回答by James
Try this:
尝试这个:
$("select").each(function(){
var select = $(this),
out = select.next();
select.change(function () {
out.text(select.val());
});
}).trigger('change');
回答by Paul Hadfield
Try this:
尝试这个:
$("select").change(function () {
var str = "";
str = $(this).find(":selected").text();
$(".out").text(str);
}).trigger('change');
回答by mld
You can get the changed element using $(this)within the event callback. Try changing the line
您可以$(this)在事件回调中使用更改的元素。尝试更改线路
str = $("select option:selected").text();
to
到
str = $(this).find("option:selected").text();

