2012-07-18 66 views
1

我似乎有,我可以不在身邊讓我的頭一個非常基本的問題,我希望有人能夠幫助我......的jQuery與去年孩子追加後

我有一個「包裝」用股利三個'網頁'div。當最右邊的div被點擊時,這個應該成爲中間的一個。我發現了一個很好的方法,首先克隆第一個子div並在最後附加它,然後動畫留下「包裝器」div,然後移除原始的第一個子div並恢復「包裝器」div的原始位置。

但問題是,這隻適用於原始DOM中的第一次點擊;也就是說,它不能將附加的div識別爲新的最後一個孩子......任何人都可以幫我解決問題嗎?

jQuery的

$(document).ready(function() { 
      $('#wrapper div:last-child').click(function() { 
       $('#wrapper').animate({'left' : '-33%' }, 500, function() { 
        $('#wrapper div:first-child').clone(true).appendTo('#wrapper'); 
        $('#wrapper div:first-child').remove(); 
        $('#wrapper').css('left', '0'); 
       }); 
      }); 
     }); 

HTML

<div id="wrapper"> 
     <div class="page" id="p1">1st</div> 
     <div class="page" id="p2">2nd</div> 
     <div class="page" id="p3">3rd</div> 
    </div> 

回答

2
$('#wrapper').on('click', 'div:last-child', function() { 
    $('#wrapper').animate({ 
     'left': '-33%' 
    }, 500, function() { 
     $('#wrapper div:first-child').clone(true).appendTo('#wrapper'); 
     $('#wrapper div:first-child').remove(); 
     $('#wrapper').css('left', '0'); 
    }); 
}); 

正如你所添加的div#wrapper動態,所以你需要委託事件處理程序。使用jQuery .on()你可以像上面那樣綁定click

.on()爲代表事件的語法是:

$(staticParent).on(eventName, targetChild, handler); 

在哪裏,staticParent指不是動態的目標元素(動態元件)的容器中。

+0

非常感謝!這完美地解決了這個問題,並且學習了關於動態添加元素及其行爲的另一件事 – 2012-07-18 20:46:33