gpt4 book ai didi

javascript - 如何使用 Bootstrap 切换被单击的元素并隐藏所有其他元素?

转载 作者:行者123 更新时间:2023-11-29 21:42:41 25 4
gpt4 key购买 nike

如何使用 bootstrap V3.5 切换被点击的元素并隐藏所有其他元素?

这是我的代码:

<div id="buttons" style="padding: 50px;">
<a data-toggle="collapse" data-target="#item-01">
<button class="btn btn-default">
Item-01
</button>
</a>

<a data-toggle="collapse" data-target="#item-02">
<button class="btn btn-default">
Item-02
</button>
</a>
</div>

<div id="itens">
<div class="collapse" id="item-01">
<span>Item 01</span>
</div>
<div class="collapse" id="item-02">
<span>Item 02</span>
</div>
</div>

DEMO页面。

最佳答案

您可能应该将 data-target 属性放在按钮本身上,但您的代码按原样...在 jQuery 中使用以下内容:

$("button").on("click", function(){
var alertMsg = $(this).parent().data("target");
alert(alertMsg); //First grab the data-target from the button's parent, or alternatively the button itself as I would recommend.
//Note, you have a typo which I moved forward with below.

/* var itemToShow = "#" + alertMsg;
alert(itemToShow); */

// I would recommend as well you don't use hashtags in your data-*
// elements. Rather as shown here, add the hashtag in with code.
$("#itens .collapse").hide(); //first hide all of the elements
$(alertMsg).show(); //then show the element related to your button click event data-target id.
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<div id="buttons" style="padding: 50px;">
<a data-toggle="collapse" data-target="#item-01">
<button class="btn btn-default">
Item-01
</button>
</a>

<a data-toggle="collapse" data-target="#item-02">
<button class="btn btn-default">
Item-02
</button>
</a>
</div>

<div id="itens">
<div class="collapse" id="item-01">
<span>Item 01</span>
</div>
<div class="collapse" id="item-02">
<span>Item 02</span>
</div>
</div>

关于javascript - 如何使用 Bootstrap 切换被单击的元素并隐藏所有其他元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32215774/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com