简体   繁体   English

仅将类添加到单击的元素及其子元素中

[英]Add class only to clicked element and it's children

I am trying to add a class to a div when another one is clicked. 我试图在单击另一个类时将一个类添加到div Whit the code I have when I click on one div all of the get the class added. 当我单击一个div ,将所有的代码添加到该类中,得到的代码就是我的。

FIDDLE 小提琴

My jQuery is: 我的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();
});

How could I solve this? 我该如何解决?

By using the this reference to current element 通过使用对当前元素的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();
    });

If you want to add the class to .front element also, then try 如果您还想将类添加到.front元素,请尝试

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

Use $(this) in the event handler to refer to the element that is clicked. 在事件处理程序中使用$(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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM