简体   繁体   English

将事件处理程序绑定到动态加载的输入

[英]Binding an event handler to dynamically loaded input

I have a pagination input field that's dynamically created after an ajax call from the main page is made to load some data. 我有一个分页输入字段,它是在从主页进行ajax调用以加载一些数据后动态创建的。 The input field is has class goto . 输入字段是class goto

So it's like this: - main page has a script with a function called loadData() - when a user makes an ajax call, a table is pulled from the database via ajax. 就像这样:-主页上有一个脚本,带有一个名为loadData()的函数-当用户进行ajax调用时,将通过ajax从数据库中提取一个表。 - this ajax data includes the pagination tabs ( First , Prev , Next , Last ), as well as the .goto field in which users can enter a page number. -该ajax数据包括分页选项卡( FirstPrevNextLast )以及.goto字段,用户可以在其中输入页码。 When the user enters a page number, the main page's loadData() function should be called. 当用户输入页码时,应调用主页的loadData()函数。

This is my code (it's on the main page): 这是我的代码(在主页上):

$('.goto').bind('keydown', function(e){
        console.log(e.which);
        if(e.which==13)
        loadData($(this).val());
    });

But nothing happens. 但是什么也没发生。 Neither the console message, nothing. 既没有控制台消息,也没有。

If the element is dynamically created, you should use the on() method while using event delegation to bind events to the element(s). 如果元素是动态创建的,则on()使用事件委托将事件绑定到元素时,应使用on()方法。

In your case, the following should work: 在您的情况下,以下方法应该起作用:

$(document).on('keydown', '.goto', function(e){
    console.log(e.which);
    if(e.which==13)
    loadData($(this).val());
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM