简体   繁体   中英

How can I combine two on click functions?

I have two on click function... somewhat like below. It is working. However, I have a feeling that the on click functions can be combined into one for optimization reasons. Basically when xx is clicked it shows some elements, hides some elements, and adds a class. When yy is clicked it does exactly the opposite. Can these be combined?

/*clicking the search icon on the top*/ 
$(".xx").on("click",function(){
        $a.show();
        $b.hide();
        $c.addClass("myClass");

}); 

/*clicking the cross icon on the top*/
$(".yy").on("click",function(){
        $c.removeClass("myClass");
        $a.hide();
        $b.show();                  
});

Yes, you can combine them with a single function. As you are hiding, showing and adding class to some elements you have to check for corresponding element which is clicked. Here's the code:

$(".xx, .yy").on("click", function(){
    if($(this).hasClass("xx")){
       $a.show();
       $b.hide();
       $c.addClass("myClass");
    }else if($(this).hasClass("yy")){
       $c.removeClass("myClass");
       $a.hide();
       $b.show();
    }
});

That's it.

Use the toggle function, described here and the toggleClass function described here .

This could look something like:

function handleClick()
{
    $a.toggle();
    $b.toggle();
    $c.toggleClass("myClass");
}

$(".xx").on("click", handleClick);
$(".yy").on("click", handleClick);

You can use attr for checking the class name also can hasClass()

$(".xx, .yy").on("click",function(){
    var c_name = $(this).attr('class');
    if(c_name == 'xx'){
        $a.show();
        $b.hide();
        $c.addClass("myClass");
    }else if(c_name == 'yy'){
        $c.removeClass("myClass");
        $a.hide();
        $b.show();
    }
});

instead of adding class to $c, add the class to a common parent, and use CSS to control visibility of $a and $b

 .a, .b {display:none;}
 .parentClass .a, .parentClass .b{
    display:block
 }

and add or removeClass depending on which element is clicked.

You could use toggle functions and pass a boolean value into them:

$(".xx, .yy").on("click",function(){
    var custBoolean = $(this).is(".xx");
    $a.toggle(custBoolean);
    $b.toggle(!custBoolean);
    $c.toggleClass("myClass", custBoolean);
});

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