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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9762231/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 11:16:08  来源:igfitidea点击:

Bind on(keyup) to dynamic elements in jQuery (Twitter Bootstrap + typehead)

jquerytwitter-bootstrapjquery-eventskeyup

提问by Jean-Philippe Murray

I guess some of you must have frowned eyebrows reading this title eh ? I'm sure people asks this every time, 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 ...

我想你们中的一些人一定在看到这个标题时皱起了眉头吧?我敢肯定人们每次都会问这个,但是,我还没有看到我的特定问题,所以,我正在尝试!将事件绑定到动态创建的元素是我的氪石,我就是无法理解它......

So ok, I'm using Twitter Boostrap, with the typehead()plugin. I'm using this trickto 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
});

Every time 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 !

每次有一个 keyup 时,脚本都会触发一个 jSON 请求,检查他的东西,并将结果返回给typehead()谁来完成这项工作的自动完成部分。那么我怎么能告诉 jQuery 查看在初始绑定之后创建的 #aDropdownID 呢?我继续检查我是否可以使用live(),但是因为on()替换了它......我一无所知!

Any help appreciated !

任何帮助表示赞赏!

回答by elclanrs

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.

回答by Mark Ryan Orosa

This works for me:

这对我有用:

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