簡體   English   中英

每個克隆的jQuery單獨功能

[英]jQuery separate function for each clone

我在使每個克隆都獨立時遇到問題,當前,如果單擊任何克隆,則整個“軍隊”將執行功能(slideToggle()),而不僅僅是我想要的一個div。

這是我的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')但沒有成功。

因為元素(除了第一個)是不是在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小提琴演示

參考文獻:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM