简体   繁体   English

如何结合两个单击功能?

[英]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. 基本上,当单击xx时,它显示一些元素,隐藏一些元素,并添加一个类。 When yy is clicked it does exactly the opposite. 单击yy时,情况恰好相反。 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 . 使用toggle功能,描述在这里toggleClass描述的功能在这里

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() 您可以使用attr来检查类名,也可以使用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 而不是将类添加到$ c中,而是将该类添加到一个公共父对象中,并使用CSS控制$ a和$ 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);
});

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

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