How to hide something when clicking again the div (already opened)

问题: I've a jQuery code that makes a menu display or hide depending on the click of another element. Right now my problem is how to make the same div button toggle display and h...

问题:

I've a jQuery code that makes a menu display or hide depending on the click of another element. Right now my problem is how to make the same div button toggle display and hide if clicked successively?

JS Fiddle

$(document).mouseup(function (e)
{
    var container = new Array();
    container.push($('#item_1'));
    container.push($('#item_2'));
    
    $.each(container, function(key, value) {
        if (!$(value).is(e.target) // if the target of the click isn't the container...
            && $(value).has(e.target).length === 0) // ... nor a descendant of the container
        {
            $(value).hide();
        }
    });
});
.item_1 {
    width: 50px;
    height: 50px;
    background: blue;
}

.item_2 {
    width: 50px;
    height: 50px;
    background: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button onclick="$('#item_1').toggle();">Open 1</button>
<label id="item_1" class="item_1">Text 1</label>
<button onclick="$('#item_2').toggle();">Open 2</button>
<label id="item_2" class="item_2">Text 2</label>

Expected: Closing the MENU when clicking again the button (it is an a href) Actual: Clicking the same a href only hides the menu.


回答1:

  • First off, adding a common class (item) to the items makes them easy to select.
  • Changing the inline bindings to have a data field lets us relate the buttons to the labels easily
  • Then we can change the logic to hide anything that is not the target
  • And finally calling toggle on the target will show/hide it in turn

$(document).on('mouseup', function (e) {
  var $items = $('.item');
  var $target = $('#'+ $(e.target).data('target'));
  
  $items.not($target).hide();
  $target.toggle();
});
.item_1 {
    width: 50px;
    height: 50px;
    background: blue;
}

.item_2 {
    width: 50px;
    height: 50px;
    background: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button data-target="item_1">Open 1</button>
<label id="item_1" class="item item_1">Text 1</label>
<button data-target="item_2">Open 2</button>
<label id="item_2" class="item item_2">Text 2</label>

  • 发表于 2018-12-31 19:29
  • 阅读 ( 113 )
  • 分类:网络文章

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除