【问题标题】:How to hide something when clicking again the div (already opened)再次单击 div 时如何隐藏某些内容(已打开)
【发布时间】:2018-12-24 18:01:26
【问题描述】:

我有一个 jQuery 代码,可以根据单击另一个元素来显示或隐藏菜单。现在我的问题是如果连续单击,如何使相同的 div 按钮切换显示和隐藏?

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>

预期:再次单击按钮时关闭菜单(它是a href) 实际:点击同一个a href只会隐藏菜单。

【问题讨论】:

  • 谢谢,抱歉,我在查看新指南和“代码”部分之前尝试过,但我无法做到。我什至尝试使用报价代码,但我做不到。

标签: jquery


【解决方案1】:
  • 首先,向项目添加一个通用类(项目)使它们易于选择。
  • 将内联绑定更改为具有数据字段让我们可以轻松地将按钮与标签相关联
  • 然后我们可以改变逻辑来隐藏任何不是目标的东西
  • 最后在目标上调用切换将依次显示/隐藏它

$(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>

【讨论】:

  • 谢谢!像魅力一样工作!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-07
  • 2018-09-29
  • 2018-03-18
  • 2020-02-23
  • 1970-01-01
相关资源
最近更新 更多