将单击处理程序绑定到动态元素

Binding click handler to dynamic element

本文关键字:动态 元素 绑定 程序 单击 处理      更新时间:2023-09-26

当我动态创建新链接时,我无法捕捉到点击事件

$("#div").html("<a href="#" id="new">new link</a>);
$("#new").click(function(e) { //doesn't catch
   e.preventDefault();
   alert('click');
}

如何将处理程序绑定到动态元素?

实际上,这对我来说很好:更新了fiddle

您的原始代码中有许多语法错误。

$("#div").html("<a href='#' id='new'>new link</a>");
fixed quotes here ------^^^                      ^
fixed missing end quote here --------------------^
// works fine!
$("#new").click(function(e) {
    e.preventDefault();
    alert('click');
});

您不能通过ID引用创建的元素,因为它还没有添加到DOM中,jQuery在DOM中搜索ID。相反,请保存对图元的引用,然后将单击附加到该引用。

var div = $('<div>').attr('id', 'div');
var link = $('<a>')
  .attr('href', '#')
  .attr('id', 'new')
  .on('click', function(e) {
    e.preventDefault();
    alert('click');
  })
  .appendTo(div);

你应该试试这个贴出

看起来它会回答你的问题。

总之,试试

$(".test").click(function () {
$.ajax({ url: 'http://.....your path...../accounts/index',
    data: {test:1},
    type: 'post',
    success: function(output) {
        //your code
             }
        }); 
});