Why does jquery behave 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 'p' color will change if i click on the 'p' not on the .box class why ? And how to i make it so that 'p' color changes when i click开发者_如何学编程 on the .box div
.toggle()
assigns event handlers to the click
event, what you want is this:
$('.box').toggle(function(){
$('p', this).css({"color" : "red"});
}, function () {
$('p', this).css({"color" : "black"});
});
Every time you wrap a new function, this
refers to the element you're dealing with (at least, for this example, see more about how closures work here), so at first it's the .box
selector match, then it's each p
inside, you want to assign a click toggle on .box
to switch p
's color, so you use a .toggle()
on .box
directly.
Another option would be to simply assign the colors in classes, and use .toggleClass()
.
Give the p
elements the black
class initially, then toggle the red
class.
CSS
.black { color: black; }
.red { color: red; }
jQuery
$('.box').click(function(){
$(this).find('p').toggleClass('red');
});
精彩评论