简体   繁体   English

将jquery事件附加到动态创建的元素(jquery加载php文件)

[英]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. 我有一个php员工目录网站,在一个表中列出了我们所有的员工(连接到mysql),您可以单击每个员工在另一个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. 当我在另一个问题( 在jQuery中,如何将事件附加到动态html元素? )上阅读时,我就是这样做的,您可以使用该格式将事件附加到动态元素。 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. 我的动态元素来自我拥有的过滤器/搜索功能,该功能将基于搜索文本框更改员工列表,该搜索文本框根据我创建的filter.php文档更改员工列表。

$('#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. 但是,当从该php文件创建那些元素时,我无法通过我的jquery访问这些元素,我不确定自己在做什么错。 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. 我看到了大约4个其他问题,答案是在功能上使用jQuery,但我尝试失败了。

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});
});

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

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