简体   繁体   English

事件未在动态生成的元素上触发

[英]Event not triggering on dynamically generated element

I have a table and in that table I have given a button to user in first column of every row to delete the row and that delete button is dynamically generated when user enter the mouse on first column and this is the code我有一张表,在该表中,我在每行的第一列中为用户提供了一个按钮以删除该行,并且该删除按钮是在用户在第一列上输入鼠标时动态生成的,这是代码

$('table').on('mouseover', "td.y-id", function () {
     $(this).append($('<a class="dlt-x" style="float: right; cursor: pointer; cursor: hand;"> <i class="fa fa-trash"></i> </a>'));
});
$('table').on('mouseleave', "td.y-id", function () {
    $('.dlt-x').remove();
});

and I registered an event to click of delete button like this我注册了一个事件来点击这样的删除按钮

$('table').on('click', 'a.dlt-x', function () {
  alert("clicked");
});

and this event is not triggering.并且此事件未触发。 I look other similar questions and try all the solutions find there related delegated binding but can't solve the problem.我查看了其他类似的问题并尝试了所有解决方案,找到了相关的委托绑定,但无法解决问题。

If you are triggering for dynamic element.如果您正在触发动态元素。 Use like below使用如下

$('body').on('click',"#dynamic_element_id",function(){
   // you code
})

To stop appending the same element append if it does not exist如果不存在,则停止追加相同的元素

 $(function() { $('table').on('mouseover', "td.y-id", function (e) { if ($('.dlt-x').length === 0) { $(this).append($('<a class="dlt-x" style="float: right; cursor: pointer;">X</a>')); } }); $('table').on('mouseleave', "td.y-id", function () { $('.dlt-x').remove(); }); $('table').on('click', 'a.dlt-x', function () { alert("clicked"); }); });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table> <tr> <td class='y-id'>1</td> </tr> <tr> <td class='y-id'>2</td> </tr> </table>

Change the event listener to mouseenter instead.将事件侦听器改为mouseenter Otherwise you'll keep appending that element if you move the mouse inside.否则,如果您将鼠标移到里面,您将继续附加该元素。

 $('table').on('mouseenter', "td.y-id", function() { $(this).append($('<a class="dlt-x" style="float: right; cursor: pointer; cursor: hand;"> <i class="fa fa-trash"></i> </a>')); }); $('table').on('mouseleave', "td.y-id", function() { $('.dlt-x').remove(); }); $('table').on('click', 'a.dlt-x', function() { alert("clicked"); });
 <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" /> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table> <tr> <td>Foo</td> <td>Bar</td> <td class="y-id">Delete</td> </tr> <tr> <td>Foo</td> <td>Bar</td> <td class="y-id">Delete</td> </tr> </table>

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

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