繁体   English   中英

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

[英]Event not triggering on dynamically generated element

我有一张表,在该表中,我在每行的第一列中为用户提供了一个按钮以删除该行,并且该删除按钮是在用户在第一列上输入鼠标时动态生成的,这是代码

$('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();
});

我注册了一个事件来点击这样的删除按钮

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

并且此事件未触发。 我查看了其他类似的问题并尝试了所有解决方案,找到了相关的委托绑定,但无法解决问题。

如果您正在触发动态元素。 使用如下

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

如果不存在,则停止追加相同的元素

 $(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>

将事件侦听器改为mouseenter 否则,如果您将鼠标移到里面,您将继续附加该元素。

 $('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