javascript JQuery 从动态生成的下拉列表中获取选定的值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33236798/
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 Get selected value from dynamically generated dropdown
提问by Prem
I have an Dropdown list which is generated dynamically
我有一个动态生成的下拉列表
the below is the code snippet of the Dropdown generated
下面是生成的下拉菜单的代码片段
<select class='selectAggregate'>
<option>Select</option>
<option>Min</option>
<option>All</option>
</select>
How can i get the Seleceted option using JQuery
如何使用 JQuery 获得 Selected 选项
EditI added the jquery code I have used
编辑我添加了我使用过的 jquery 代码
$('.selectAggregate').each(function()
{
var $val = $("option:selected",this).text();
}
selectAggregate
is the class attribute of dynamically generated dropdowns
selectAggregate
是动态生成的下拉列表的类属性
回答by Satpal
Based on assumptions that you are using "direct" bindingwhich will only attach to element that exist on the page at the time your code makes the event binding call.
基于您使用“直接”绑定的假设,该绑定只会附加到您的代码进行事件绑定调用时页面上存在的元素。
You need to use Event Delegationusing .on()delegated-events approach, when generating elements dynamically or manipulation selector (like removing and adding classes).
在动态生成元素或操作选择器(如删除和添加类)时,您需要使用.on()委托事件方法使用事件委托。
General Syntax
一般语法
$(document).on('event','selector',callback_function)
Example
例子
$(document).on('change', ".selectAggregate", function(){
alert($(this).val())
});
In place of document
you should use closest static container.
代替document
您应该使用最近的静态容器。
The delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, we can use delegated events to bind the click event to dynamically created elements and also to avoid the need to frequently attach and remove event handlers.
委托事件的优点是它们可以处理来自稍后添加到文档的后代元素的事件。通过选择一个在附加委托事件处理程序时保证存在的元素,我们可以使用委托事件将点击事件绑定到动态创建的元素,并避免频繁附加和删除事件处理程序的需要。
回答by Rolwin Crasta
Try this
试试这个
$("button").click(function(){
$.each($(".selectAggregate option:selected"), function(){
var $val = $(this).text();
});
});
回答by Mangy 007
$(document).on('change','.selectAggregate', function() {
var temp = $('.selectAggregate').children(":selected").text();
});
This will help you out, here you can get the value of dynamically generated select. the change event is used because the element inside select (option) is being generated dynamically.
这将帮助您,在这里您可以获取动态生成的 select 的值。使用 change 事件是因为 select (option) 中的元素是动态生成的。
回答by WisdmLabs
To get selected value you can use following statement in your js file.
要获得选定的值,您可以在 js 文件中使用以下语句。
$(".selectAggregate option:selected").val();