元素未检测到单击事件

Element not detecting click event

本文关键字:单击 事件 检测 元素      更新时间:2023-09-26

我通过javascript动态生成HTML,并在一个表单元格中包含两个字形。铅笔字形响应正确,但我的删除代码没有,我不知道为什么。

这是呈现的HTML

<span id="edit-dp" class="glyphicon glyphicon-pencil" data-action-url="/Settings/GetDatapoint" data-id="3"></span>
<span id="delete-dp" class="glyphicon glyphicon-trash" data-id="3"></span>

下面是我的javascript代码,用于将事件绑定到元素。

$(document).ready(function(){
  $('#delete-dp').click(function (event) {
      alert('pressed');
      //add the datapoint ID to the array to be serialised to JSON and then stored in a html hidden field
      deletedDatapoints.push($(this).data('id'));
  });
})

使用.on()

$(document).ready(function(){
    $(document).on('click', '#delete-dp', function (event) {
        alert('pressed');
        //add the datapoint ID to the array to be serialised to JSON and then stored in a html hidden field
        deletedDatapoints.push($(this).data('id'));
    });
});

您可以将其范围扩大到非动态生成的最接近的父级,以便比document更高效。

要处理动态添加的事件,请使用

$('#delete-dp').on('click',function(event){
    //do your stuff
});