gpt4 book ai didi

javascript - 显示和隐藏 jQuery 选项卡

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:44:46 26 4
gpt4 key购买 nike

我有以下配置:

var pageone = document.getElementById("pageone"),
pagetwo = document.getElementById("pagetwo"),
pagethree = document.getElementById("pagethree"),
bfpone = document.getElementById("buttonone"),
bfptwo = document.getElementById("buttontwo"),
bfpthree = document.getElementById("buttonthree");
$(pagetwo).hide();
$(pagethree).hide();
$(bfpone).click(function () {
$(pageone).show();
$(pagetwo).hide();
$(pagethree).hide();
});
$(bfptwo).click(function () {
$(pageone).hide();
$(pagetwo).show();
$(pagethree).hide();
});
$(bfpthree).click(function () {
$(pageone).hide();
$(pagetwo).hide();
$(pagethree).show();
});
.page{
background:red;
color:white;
margin:2em;
padding:1em;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="buttonone">Btn one</div>
<div id="buttontwo">Btn two</div>
<div id="buttonthree">Btn three</div>
<div id="pageone" class="page">Pageone</div>
<div id="pagetwo" class="page">Pagetwo</div>
<div id="pagethree" class="page">Pagethree</div>

当点击特定于页面的 div 时,所选页面显示,而其他页面隐藏。

它工作正常,但我想要一个更高效的 jQuery 脚本,当我添加任意数量的页面时,无需修改即可工作(或者至少无需添加更多代码即可工作)。唯一的条件是它必须仅使用 javascriptjQuery

谢谢。

最佳答案

您可以使用如下的通用解决方案,而不是为每个元素使用单独的处理程序

var $pages = $('.page');
$pages.slice(1).hide();
$('.trigger').click(function() {
var $target = $('#' + $(this).data('target')).show();
$pages.not($target).hide()
});
.page {
background: red;
color: white;
margin: 2em;
padding: 1em;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="trigger" data-target="pageone">Btn one</div>
<div class="trigger" data-target="pagetwo">Btn two</div>
<div class="trigger" data-target="pagethree">Btn three</div>
<div id="pageone" class="page">Pageone</div>
<div id="pagetwo" class="page">Pagetwo</div>
<div id="pagethree" class="page">Pagethree</div>

关于javascript - 显示和隐藏 jQuery 选项卡,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31380503/

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