1

I dynamically attached a div element using jQuery on method, but when i attach a listener to the dynamically updated element it doesn't work?

HTML

<input class="123" type="button" value="button" />
<input class="123" type="button" value="button" />
<div id="footer"></div>

jQuery

$(document).ready(function () {
  $('.onlineUsers').on('click', function () {
      $('#footer').append("<div class=\"chatboxes\"> <div class=\"close\"><a href=\"#\">x</a></div> </div>");
  });

    $('a').on('click', function () {
        alert("hello");
    });
});
4

1 回答 1

2

使用.on()

由于元素是动态添加的,因此您不能将事件直接绑定到它们。因此您必须使用事件委托

$('#footer').on('click','a',function () {
     alert("hello");
});

句法

$( elements ).on( events, selector, data, handler );
于 2013-10-26T14:20:26.043 回答