绑定(keyup)到jQuery中的动态元素(Twitter Bootstrap + typehead)

时间:2021-02-06 00:01:30

I guess some of you must have frowned eyebrows reading this title eh ? I'm sure people asks this everytime, yet, I haven't seen my particular question around so, I'm trying ! Binding events to dynamically created elements is my kryptonite, I just can't wrap my head around it ...

我想你们中的一些人必须皱起眉头读这个标题呃?我相信人们每次都会问这个问题,然而,我还没有看到我的特殊问题,我正在努力!将事件绑定到动态创建的元素是我的kryptonite,我只是无法绕过它...

So ok, I'm using Twitter Boostrap, with the typehead() plugin. I'm using this trick to make it work with remote sources of data. At this point, everything work. I click on a text input in my form, tagged for it, and the scripts go load external sources and the drop down appears. But I have dynamic element creation, and you've figured, it just won't work on them. I was exploring the live() method, but looking at "how" the scripts is getting fired, I'm just not sure how I can implement it.

好吧,我正在使用带有typehead()插件的Twitter Boostrap。我正在使用这个技巧使它与远程数据源一起工作。在这一点上,一切正常。我单击表单中的文本输入,为其标记,脚本将加载外部源并显示下拉列表。但我有动态元素创建,你已经想到,它只是不会对它们起作用。我正在探索live()方法,但看看脚本被触发的“方式”,我只是不确定如何实现它。

$('#anInputField').typeahead().on('keyup', function(ev){
 // stuff happens
});

Everytime there is a keyup, the script fires a jSON request, checks his things, and gets the result back to typehead() who does the autocomplete part of the job. So how can I say to jQuery to look at #aDropdownID created after the initial binding? I went on and checked if I could use live(), but since on() replaces it... I'm clueless !

每次有密钥时,脚本都会触发一个jSON请求,检查他的东西,并将结果返回给执行作业自动完成部分的typehead()。那么我怎么能说jQuery来看看初始绑定后创建的#aDropdownID呢?我继续检查我是否可以使用live(),但是因为on()取代它...我很无能为力!

Any help appreciated !

任何帮助赞赏!

2 个解决方案

#1


41  

For on() to be able to delegate you have to call it on a static element that you know is always going to be there and then you pass the dynamic element like:

对于on()能够委托你必须在一个你知道总是在那里的静态元素上调用它,然后你传递动态元素,如:

$('#static-parent').on('keyup', '#aDropdownID', function(ev){
 // stuff happens
});

If you don't have a static parent element, then you can always use body.

如果您没有静态父元素,则可以始终使用body。

#2


9  

This works for me:

这对我有用:

$(document).on('keyup', '#YourInputFieldId', function () {
    //stuff happens
});

#1


41  

For on() to be able to delegate you have to call it on a static element that you know is always going to be there and then you pass the dynamic element like:

对于on()能够委托你必须在一个你知道总是在那里的静态元素上调用它,然后你传递动态元素,如:

$('#static-parent').on('keyup', '#aDropdownID', function(ev){
 // stuff happens
});

If you don't have a static parent element, then you can always use body.

如果您没有静态父元素,则可以始终使用body。

#2


9  

This works for me:

这对我有用:

$(document).on('keyup', '#YourInputFieldId', function () {
    //stuff happens
});