开发者

jQuery delegate problem

This is my first question on SO, so if it seems beyond dumb, please take it easy on me. I have a page with a list of pictures with links for deletion underneath them and with possibility to add more pictures. After each one of this events (that does a #user_gallery load like below, I have to click twice the delete link for it to work. Why is that ?

$('body').delegate(".delete", "click", function(e){
        $('.delete').click(function(ev){
           var pic_id = $(this).attr('id').replace('pic_', '') ;
           $.post(   'unpublish_pics.php',
                     {pic: pic_id, action:'delete'},
                     function(data)
                     {    开发者_运维问答                        
                            $('#user_gallery').load("pictures_display.php");
                     },"json"
                 );
           ev.preventDefault();
        });
        e.preventDefault();
   });

The html is goes something like this.

<div id="user_gallery">    
<div class="image">
   <a rel="gallery" class="img" href="pic.png"><img src="pic.png"></a>
    <a id="pic_1" class="ui-state-default ui-corner-all delete" href="#">Delete</a>
</div>


You don't need that .click() handler/wrapper underneath, just the .delegate() like this:

$('body').delegate(".delete", "click", function(e){
  var pic_id = $(this).attr('id').replace('pic_', '');
  $.post('unpublish_pics.php', {pic: pic_id, action:'delete'}, function(data) {                            
    $('#user_gallery').load("pictures_display.php");
  },"json");
  e.preventDefault();
});

Currently you're binding a .click() handler for the next click...if you want to perform an action when it's clicked just place the code right in the .delegate() handler.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜