简体   繁体   中英

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. The input field is has 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. - 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. When the user enters a page number, the main page's loadData() function should be called.

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).

In your case, the following should work:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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