简体   繁体   中英

jQuery .click() not firing as expecting

What I'm trying to achieve is:

  • User click h4 inside of a .question div
  • .question div is expanded to 90px, and it's child paragraph slides into view by having its margin-top set to 0
  • When the user clicks the h4 element a second time, the .question div should return to 35px height and the paragraph should have margin-top set to 35px.

Here's a Fiddle

jQuery(document).ready(function($) {
    $('.question h4').click(function () {
        $(this).parents('.question').css('height', '90');
        $(this).siblings('p').css('margin-top', '0');
        $(this).parent().addClass('open');
    });

    $('.question.open h4').click(function () {
        $(this).parent.removeClass('open');
        $(this).parents('.question').css('height', '65px');
        $(this).siblings('p').css('margin-top', '35px');
    });
});

Your first click handler is firing even if .question is .open . You need to exclude .open from the first selector.

$('.question:not(.open) h4').click(...

As Pointy mentioned, you only need 1 handler with a conditional statement. Also, for speed, overhead, and simplicity, I would consider stringing all desired action on a node into one line (ie, anything you want to do with a $(this).parent() should be stringed together so jQuery only has to parse the DOM one time).

$('.question h4').click(function () {
    if (!$(this).parent().hasClass('open')){
        $(this).parents('.question').css('height', '90').addClass('open');
        $(this).siblings('p').css('margin-top','0');
    }else{
        //$(this).parents('.question').css('height', '65px');
        $(this).parent().css('height', '65px').removeClass('open');
        $(this).siblings('p').css('margin-top', '35px');
    }
});

You really just need one handler:

$('.question h4').click(function () {
    if ($(this).is('.open h4')) {
        $(this).parent.removeClass('open');
        $(this).parents('.question').css('height', '65px');
        $(this).siblings('p').css('margin-top', '35px');
    }
    else {
        $(this).parents('.question').css('height', '90');
        $(this).siblings('p').css('margin-top', '0');
        $(this).parent().addClass('open');
    }
});

Your second handler assignment does nothing because none of your <h4> elements start off with the "open" class (or, at least, I suspect they don't).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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