简体   繁体   中英

jQuery Live() doesn't work

Hi from some reason my live() function doesn't work. i want to add a mew li element with click functionality by clicking on li element inside the ulAllApps. a new li element created inside the ulMyApps but without the click functionality.

HTML:

<div class="MyApps" >
  <ul class="ulMyApps">   
       <li class="MYLinkTR">app1</li>
   </ul>     
</div>
<div class="AllApps">
   <ul class="ulAllApps"> 
       <li class="IECLinkTR">app1</li>
       <li class="IECLinkTR">app2</li>
   </ul>
</div>

jQuery code:

$(document).ready(function () {

$(".IECLinkTR").click(function () { 
    var tmp = $(this).html();
    $.ajax({
        type: "POST",
        url: window.location.href+"/addToMyLinks",
        data: "{'app': '" + tmp  + "'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (msg) {
           $(".ulMyApps").append("<li class=\"MYLinkTR\">"+ tmp +"</li>");
        },
        error: function (msg) {
           alert("You have already have that app");                 
        }
    }); 
});

$(".MYLinkTR").live('click', function () {
    var tmp = $(this);
    $.ajax({
        type: "POST",
        url: window.location.href + "/removeFromMyLinks",
        data: "{'app': '" + $(this).html() + "'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (msg) {
            tmp.closest('li').remove();
        },
        error: function (msg) {
        }
    });
});
});

from some reason the new li element created dynamically dont have the CLICK functionality coming from the Live function......

All I can see is that on your MYLinkTR click function you are trying to remove the tmp.closest('li'). Now looking at the docs I think closest is moving up the DOM looking for the closest next ('li') rather then the one it is on. Are you sure you don't want tmp.remove()?

Perhaps seeing if an alert is thrown first on the click to see if it is firing as you don't do anything on error. Something might be happening here that you are not aware of. The other options is changing LIVE to delegate and attaching this to the ul and see if this fires

 $('ul.MyApps').delegate('li', 'click', function(e){
       alert('does this at least fire');
  });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM