2014-05-25 103 views
0

我有一個使每個克隆獨立的問題,目前如果我點擊任何克隆,整個「軍隊」將執行函數(slideToggle()),而不僅僅是單個我想要的div。每個克隆的jQuery單獨功能

因此,這裏是我的jQuery腳本

$(document).ready(function(){ 
    $(".box").click(function(){ 
     $(".resource").slideToggle(); 
     }); 
    $('#clone').click(function(){ 
     $('div:first').clone().appendTo('body'); 
    }); 
}); 

而我的身體

<body> 
<button id="clone">Add item</button> 
<div class="my_inventory"> 
    <div class="box"> 
    <h2>CLICK HERE</h2> 
    </div> 

    <div class="resource"> 
    <p>CONTENT HERE</p> 
    </div> 
</div> 
</body> 

總括來說,我希望每個克隆的「盒子」,以開放和關閉自身點擊各自的<h2>

我的猜測是,我需要在地址this而不是在jQuery中的類,但我一直在嘗試$(this).find('.resource')沒有任何成功。

+1

代碼中缺少一些東西。帶有「克隆」標識的元素在哪裏創建? –

+0

除了沒有'id =「clone」'你真的沒有解釋到究竟是什麼問題 – charlietfl

+0

對不起,只是編輯,使其更清晰 – vagaryblue

回答

0

由於當綁定事件處理程序時,元素(除第一個之外)不在DOM中,所以需要將事件處理委託給DOM中的一個祖先,其中的,在這種情況下,存在最近的祖先是body元件,因此:

// selecting the closest ancestor element to the dynamically-added elements 
// that is present in the DOM at the point of event-binding: 
$('body') 
// using on() to listen for the event(s) (in this case 'click') that occurs on 
// the '.box' element(s), 
// and then executes the anonymous function: 
.on('click', '.box', function() { 
    // looks to the parent of the clicked-element: 
    $(this).parent() 
    // finds the '.resource' element(s): 
    .find('.resource') 
    // applies the slideToggle() method: 
    .slideToggle(); 
}); 

JS Fiddle demo

參考文獻: