简体   繁体   English

3按钮Jquery开/关和开/关

[英]3 button Jquery on/off and both on/off

I have 3 buttons: button 1, button 2 and button 3. button 1 toggles show/hide of the left side. 我有3个按钮:按钮1,按钮2和按钮3。按钮1切换左侧的显示/隐藏。 button 2 does the same but does the right side. 按钮2的功能相同,但右侧的功能相同。 Button 3 does both sides. 按钮3两侧都有。 What is the right way to do this? 什么是正确的方法?

https://jsfiddle.net/anthony0perez/m9h2n1vk/2/ https://jsfiddle.net/anthony0perez/m9h2n1vk/2/

<div id="list-map-button" class="btn map-btn">LIST</div>
<div id="map-map-button" class="btn map-btn">MAP</div>
<div id="both-map-button" class="btn map-btn map-btn-active">BOTH</div>
<br style="clear:both;"/>
<div class="container">
    <div id="left_side">
        map side
        <div  id="block-3">Block 3</div>
        <div id="block-4" class="not-active-block">Block 4</div>
    </div>
    <div id="right_side">
        list side
        <div id="block-5">Block 5</div>
        <div id="block-6" class="not-active-block">Block 6</div>
    </div>
    <br style="clear:both;"/>
</div>

    $(document).ready(function(){    
    $( "#both-map-button" ).click(function() {
        //alert('clicked both button');
        $("#block-4, #block-3, #block-5, #block-6").hide();
        $("#block-4, #block-3, #block-5, #block-6").addClass("acvite-btn");

        $("#block-4, #block-3").show();
        $("#block-5, #block-6").show();

    });
    $( "#map-map-button" ).click(function() {
        //alert('clicked map button');
        $("#block-5").toggle();
        $("#block-6").toggle();
    });
    $( "#list-map-button" ).click(function() {
         //alert('clicked list button');
        $("#block-4").toggle();
        $("#block-3").toggle();
    });
 });

You could simply use a single variable to hold your state. 您可以只使用一个变量来保存状态。 Note that I hard-coded the loops for the example since we're always dealing with three buttons. 请注意,由于我们总是处理三个按钮,因此我对示例循环进行了硬编码。

 inputs = document.getElementsByTagName('input'); state = 0; for (var i = 0; i < 3; i++) { (function(i) { inputs[i].addEventListener('click', function() { state ^= (i + 1); for (var j = 1; j < 3; j++) { inputs[j - 1].classList.toggle('on', (j & state)); } }); }(i)); } 
 input { background: lightgray } input.side { background: red } input.on { background: limegreen } 
 <input type="button" class="side" value="toggle left" /> <input type="button" class="side" value="toggle right" /> <input type="button" value="toggle both" /> 

If you're instead looking to turn both toggles on if one is already on, you can simply add a separate check for that. 如果您想同时打开两个开关,则只需为其添加单独的检查即可。

if (i & 2) {
    state = ~~(state > 0) * 3;
}

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

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