2016-04-28 82 views
0

我試圖添加一個類到div當另一個被點擊。 用白色代碼我點擊一個div所有得到的類添加。只將類添加到單擊的元素,它的孩子

FIDDLE

我jQuery是:

$(".front").click(function (event) { 
    // remove classes from all 
    $('.front .back').not($(this)).removeClass('back-Active'); 
    // add class to the one we clicked 
    $('.front .back').addClass("back-Active"); 
    event.stopPropagation(); 
}); 

我怎麼能解決這個問題?

回答

1

使用$(this)在事件處理程序參照被點擊的元素。

$('.back', this)    // Select the element inside clicked element having `back` class 
    .addBack(this)   // Add clicked element to the set 
    .addClass("back-Active"); // Add class on the elements 

Updated Fiddle

$(document).on('click', function() { 
 
    $('.back').removeClass("back-Active"); 
 
}); 
 

 

 
$(".front").click(function(event) { 
 
    // remove classes from all 
 
    $('.back-Active').removeClass('back-Active'); 
 
    // add class to the one we clicked 
 
    $('.back', this).addBack(this).addClass("back-Active"); 
 
    event.stopPropagation(); 
 
});
.back-Active { 
 
    transform: scale(1.0) !important; 
 
    opacity: 1 !important; 
 
    transition: 400ms ease; 
 
} 
 

 
.front { 
 
    background-color: red; 
 
    width: 100px; 
 
    height: 100px; 
 
    margin: 20px; 
 
} 
 

 
.back { 
 
    transform: scale(0.0); 
 
    opacity: 0; 
 
    background-color: green; 
 
    width: 100px; 
 
    height: 100px; 
 
    margin-top: -18px; 
 
    transition: 400ms ease; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> 
 
<div class="front"> 
 
    AAA 
 
    <div class="back">AAA-BACK</div> 
 
</div> 
 

 
<div class="front"> 
 
    BBB 
 
    <div class="back">BBB-BACK</div> 
 
</div> 
 

 
<div class="front"> 
 
    CCC 
 
    <div class="back">CCC-BACK</div> 
 
</div> 
 

 
<div class="front"> 
 
    DDD 
 
    <div class="back">DDD-BACK</div> 
 
</div>

2

到如果要將該類添加到.front元素也使用this參考當前元素

$(".front").click(function (event) { 
     // remove classes from all 
     $('.front .back').removeClass('back-Active'); //line changed to remove back-Active from all 
     // add class to the one we clicked 
     $(this).find('.back').addClass("back-Active"); //this line changed to add back-Active to only current element 
     event.stopPropagation(); 
    }); 

,然後嘗試

$(".front").click(function (event) { 
     $('.front, .front .back').removeClass('back-Active'); 
     $(this).addClass("back-Active"); 
     $(this).find('.back').addClass("back-Active"); 
     event.stopPropagation(); 
    }); 
+0

OP要添加類的點擊('.front')元素太多,不只是孩子 - '.back'。 – Tushar

+0

@Tushar更新了代碼,沒有注意到前面的元素也會有相同的類。謝謝 – gurvinder372

相關問題