简体   繁体   中英

Attach jquery events to dynamically created elements (jquery load php file)

I have a php employee directory website that lists all our employees in a table (connected to mysql), and you are able to click each employee to open up their details in another div.

$('.emptab').click(function(event) {
    var status = $(this).attr('id');
    $("#empview").load("employee.php", {'data': datastring, 'current': status});
});

I originally had the above code, but needed to be able to attach events to dynamic elements, so I changed to the following code:

$('tbody').on('click', 'tr.emptab', function() {
    var status = $(this).attr('id');
    $("#employeedetails").load("employee.php", {'data': datastring, 'current': status});
});

I did it that way as I read in another question ( In jQuery, how to attach events to dynamic html elements? ) that you can use that format to attach events to dynamic elements. Just to clarify, this code continues to work with the initial page, but fails after the search filter is used.

My dynamic elements comes from a filter/search function I have that will change the list of employees based on a search text box which changes the list of employees based on a filter.php document I created.

$('#search').on('input propertychange paste', function() {
    var string = $('#search').val();
    $("#employeelist").load("filter.php", {'data': datastring, 'search': string});
});

However, when those elements are created from that php file, I am unable to access the elements through my jquery, I'm not sure what I'm doing wrong. There were about 4 other questions I saw where the answer was to use the jquery on function, which I've tried with no success.

Thanks for your time.

You can use following code for this

$(document).on('click', '.emptab', function() {
    var status = $(this).attr('id');
    $("#employeedetails").load("employee.php", {'data': datastring, 'current': status});
});

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