我有一个动态生成的下拉列表
下面是生成下拉列表的代码片段
<select class='selectAggregate'>
<option>Select</option>
<option>Min</option>
<option>All</option>
</select>
如何使用 JQuery 获取 Selected 选项
编辑 我添加了我用过的jquery代码
$('.selectAggregate').each(function()
{
var $val = $("option:selected",this).text();
}
selectAggregate
是动态生成下拉框的类属性
最佳答案
基于您使用“直接”绑定(bind)的假设,它只会附加到您的代码进行事件绑定(bind)调用时页面上存在的元素。
您需要使用 Event Delegation使用 .on()委托(delegate)事件方法,当动态生成元素或操作选择器(如删除和添加类)时。
一般语法
$(document).on('event','selector',callback_function)
例子
$(document).on('change', ".selectAggregate", function(){
alert($(this).val())
});
代替 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.
关于javascript - JQuery 从动态生成的下拉列表中获取选定的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33236798/