Alternative to jquery live that can work

2019-01-25 13:15发布

I have this simple code. http://jsfiddle.net/borth/BmEZv/ If you click on the link once, it works fine. If you click on it a second time, it doesn't work. Due to the html being loaded into html after the DOM has loaded, I've tried .on, .bind, .delegate, and .live. No of them work except for .live which is being deprecated (I'm using jquery 1.7.2).

Can someone explain why .live is the only function that works and why the others don't work (or if I am doing something wrong with the other functions).


$(document).ready(function(){
  $(".OpenPopup").bind('click', function(e){
      alert('test .OpenPopup');
      // do something
      return false;
  });
  $(".EditIcon").bind('click', function(){
      alert('test .EditIcon');
      // do something
      $("#ABC").html('<div class="EditIcon OpenPopup" pwidth="800" pheight="500" ptitle="EditText">click here again</div>');
  });
});


<div id="ABC"><div class="EditIcon OpenPopup" pwidth="800" pheight="500" ptitle="EditText">click here</div></div>

3条回答
Emotional °昔
2楼-- · 2019-01-25 13:47

.on() can be used with or without delegation, below is an example of on() using delegation.

$("#ABC").on('click', ".OpenPopup", function(e){

http://jsfiddle.net/BmEZv/1/

查看更多
做个烂人
3楼-- · 2019-01-25 14:04
$(document).ready(function(){
        $(document.body).on('click', ".OpenPopup", function(e){
            alert('test .OpenPopup');
            // do something
            return false;
        });
        $(document.body).on('click', ".EditIcon", function(){
            alert('test .EditIcon');
            // do something
            $("#ABC").html('<div class="EditIcon OpenPopup" pwidth="800" pheight="500" ptitle="Edit Text">click here again</div>');
        });
    });
查看更多
乱世女痞
4楼-- · 2019-01-25 14:05

Following @Dhofca this really worked. I am just showing an example which I tried with 'this' keyword.

$(document.body).on('click', ".query-result table tr", function () {
    var el = $(this);
    el.closest('table').find('tr').removeClass('dotted');
    el.addClass('dotted');
});
查看更多
登录 后发表回答