使用jQuery将事件附加到动态创建的选择选择 [英] Attach event to dynamically created chosen select using jQuery
问题描述
我想添加事件动态创建选择的选择,并希望获得选项值..
但混淆了如何触发事件动态创建选择选择...?
我知道我们可以使用 jquery.live或jquery.on event
,但为此我们需要适当的选择器/ id
$(document).on(eventName,selector,function(){});
我的小提琴: Demo小提琴
html:
< select id =t1pl1class =chosen-selectdata-placeholder =Select player ...style =width:200px;>
< option value =0>< / option>
< option value =11> Player 1< / option>
< option value =12>玩家2< / option>
< option value =13>玩家3< / option>
< / select>
演示: http://jsfiddle.net/4wCQh/23/
我想你可以在上使用来进行事件绑定,并且由于您有动态元素,因此您应该使用
select
的父选择器来进行事件绑定。
简单的解决方案就是使用这个:
$(document ).on('change','select [id ^ =t1]',function(){
alert($(this).val());
});
使用此代码进行更新:
<$ p $($)$($#$)$(#pid)。$($)$(文档).on('mouseenter','li.active-result.highlighted', (option)。eq($(this).data(option-array-index)).val());
});
而不是您的旧代码。
解释:
$ b select [ id ^ =t1]
是以 t1
开头的所有select的css选择器。有关更多信息,请参阅属性选择器。此外,您可以使用 $(this).val()
select $ bI want to add event to dynamically created chosen select and want to get option value..
but confuse how to fire event on dynamically created chosen select...?
I know we can use jquery.live or jquery.on event
but for that we need proper selector/id
$(document).on( eventName, selector, function(){} );
My fiddle : Demo Fiddle
html :
<select id="t1pl1" class="chosen-select" data-placeholder="Select player..." style="width:200px;">
<option value="0"></option>
<option value="11">Player 1</option>
<option value="12">Player 2</option>
<option value="13">Player 3</option>
</select>
解决方案 Demo: http://jsfiddle.net/4wCQh/23/
I think you can use on
for event binding and since you have dynamic elements, you should use the parent selectors of select
for event binding.
Simple solution will be to use this:
$(document).on('change', 'select[id^="t1"]', function () {
alert($(this).val());
});
Use this code for updation:
$(document).on('mouseenter', 'li.active-result.highlighted', function (e) {
$("#pid").html($("option").eq($(this).data("option-array-index")).val());
});
instead of your old code.
Explanation:
change
is the event, select[id^="t1"]
is the css selector for all the select having id starting with t1
. Refer Attribute Selectors for more information. Further you can get the current value of select
using $(this).val()
这篇关于使用jQuery将事件附加到动态创建的选择选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!