开发者

Not able to delete list which dynamically created with jquery

I have two html here. The first one is dynamically generated by php and second one is just html to test.

I also have the following jquery.

When I click a cross with class delete in the second ones(plain html), it works nicely. However when I click a cross in the first ones, it does not work. It redirect me to the home page with # at the end.

I am hoping someone point out what I am doing wrong.

Thank in advance.

HTML

First part (dyanmicall generated)
<ul style="display: block;" id="message">
<li class="41">
<span class="user"><strong>shin</strong></span>
<span class="msg">  delete this as well</span>
<span class="date">2010-01-15 07:47:31</span>
<a href="#" id="41" class="delete">x</a>
    <div class="clear"></div></li>
<li class="40">
<span class="user"><strong>shin</strong></span>

<span class="msg">  delete me as well</span>
<span class="date">2010-01-14 16:01:44</span>
<a href="#" id="40" class="delete">x</a>
    <div class="clear"></div></li>
...
...</ul>


Se开发者_StackOverflow社区cond part which is plain html
    <ul id="another">
    <li><a href="#">you can't delete me</a></li>
    <li><a href="#" class="delete">delete this</a></li>
    <li><a href="#" class="delete">delete this</a></li>
    </ul>

Here is jquery

$(".delete").click(function(event) {
    event.preventDefault();


loading.fadeIn();
var commentContainer = $(this).parent();
var id = $(this).attr("id");
// var string = 'id='+ id ;

$.ajax({
   type: "POST",
   url: "index.php/admin/messages/changestatus/"+id,
   // data: string,
   cache: false,
   success: function(){
    commentContainer.slideUp('slow', function() {$(this).remove();});
    loading.fadeOut();
  }

 });


return false;
    });

I am using CodeIgniter by the way.


When you do this: $(".delete").click(handler); what you're doing is finding all class="delete" that exist at that time and binding a click handler to them, but those dynamic ones don't exist then, so they never get that handler.

To fix this, use .live() which handles the event in a different way, it sits at the root of the DOM waiting for the click to bubble up, and if the target of the click matches the selector, then the handler executes...new and old elements bubble the same way, so it doesn't care when it was added :)

To use .live(), just replace this:

$(".delete").click(function(event) {

With this:

$(".delete").live('click', function(event) {


Your code looks like it should work fine. That means one of a few things is probably occurring:

  1. You don't have jQuery properly loaded, or it is loading but your code ins't in the document.ready function.
  2. One of the other items isn't defined (like loading) and as such is throwing a JS error, causing your whole click event to fail.

Try clicking the link with Firebug open and seeing if a JS error is being thrown when you click the link.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜