从JQuery动态创建的数据中获取单击事件

时间:2022-09-17 10:54:52

The code below is generated dynamically using an Ajax call and placed in a hardcoded div called studentresults.

下面的代码是使用Ajax调用动态生成的,并放在名为studentresults的硬编码div中。

<div id="studentresults" class="row span8 offset2">
  <table id="tablestudent" class="table table-striped table-hover center-table">
    <thead>Heading for my table</thead<
      <tbody>
        <tr id="showstudents">
          <td>29041</td>
          <td>jan</td>
          <td>jan</td>
          <td>
            <a class="btn" href="#">View Results »</a>
          </td>
          <td id="29041">
            <a id="29041" class="btn showstudent" href="#">Delete Student » </a>
          </td>
        </tr>
        <tr id="showstudents">
           .... another dynamic record from Ajax...
        </tr>
     </tbody>
  </table>
</div>

That works fine. However I would like a another Ajax call on the Delete Student tag. I cannot understand how to write the jQuery click function for this dynamic content.

工作的很好。但是,我希望在Delete Student标记上进行另一个Ajax调用。我不明白如何为这个动态内容编写jQuery单击函数。

The JQuery call doesn't work

JQuery调用不起作用

$('.showstudent').click(function(){

 alert('In click');

});

However this works in the hard coded div container

但是这在硬编码的div容器中是有效的

 $('#studentresults').click(function () {

 alert('In click');

});

How can I access the dynamic <a> content

如何访问动态内容

1 个解决方案

#1


3  

In case of dynamic elements you need use event propagation based event listeners.

对于动态元素,需要使用基于事件传播的事件侦听器。

When you use $('.showstudent').click(..) to register an event handler, it executes the selector at the execution time and the dynamic elements may not be present at that time, thus the event handlers will not get attached to those elements

当您使用$('.showstudent').click(..)来注册一个事件处理程序时,它会在执行时执行选择器,而动态元素此时可能不存在,因此事件处理程序不会附加到这些元素上

$(document).on('click','.showstudent', function(){
    alert('In click');
});

#1


3  

In case of dynamic elements you need use event propagation based event listeners.

对于动态元素,需要使用基于事件传播的事件侦听器。

When you use $('.showstudent').click(..) to register an event handler, it executes the selector at the execution time and the dynamic elements may not be present at that time, thus the event handlers will not get attached to those elements

当您使用$('.showstudent').click(..)来注册一个事件处理程序时,它会在执行时执行选择器,而动态元素此时可能不存在,因此事件处理程序不会附加到这些元素上

$(document).on('click','.showstudent', function(){
    alert('In click');
});