Why jquery behaves like this

$('.box').click(function(){
    $(this).find('p').toggle(
        function () {
            $(this).css({"color" : "red"});
        },
        function () {
            $(this).css({"color" : "black"});
        }
    );
});

if I execute this script the color "p" will change, if I click on "p" and not on the .box class why? And how to make the color "p" change when I click on the .box div

+3
source share
2 answers

.toggle()assigns event handlers to the event clickthat you want:

$('.box').toggle(function(){
    $('p', this).css({"color" : "red"});
},  function () {
    $('p', this).css({"color" : "black"});
});

, , this , ( , . , ), .box, p , .box p, .toggle() .box.

+7

- .toggleClass().

p black, red.

CSS

    .black { color: black; }
    .red { color: red; }

JQuery

$('.box').click(function(){
        $(this).find('p').toggleClass('red');
});
+1

Source: https://habr.com/ru/post/1749404/


All Articles