这是我在开始 JS 开发时不断遇到的问题。问题概要如下。我们有N
页面上的按钮数量。我们想为每个按钮创建一个事件监听器。假设按钮的名称是:"overview-tab"
, "return-tab"
和 "analysis-tab"
.我们还有div
具有与按钮名称相对应的类名称。例如,<div class="overview-tab"></div>
.最初,只有一个 div 是可见的。假设它是 overview-tab
.目标是display: none
所有 div
s,但是用户单击按钮的那个。我总是从以下开始,但随后意识到第二个 each
的内部, 我无权访问 button
的名称从上面each
:
$(":button").each(function(index, buttonElement) {
$(element).on('click', function(err) {
if(err) throw err;
$(".tabs").each(function(index, tabElement) {
// set all of the tabs, but the one clicked on (buttonElement)
// to display: none.
});
});
});
HTML代码:
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
</head>
<body>
<input type="button" name="overview-tab" value="Overview Tab">
<input type="button" name="return-tab" value="Return Tab">
<input type="button" name="analysis-tab" value="Analysis Tab">
<div class="overview-tab" style="background:red; width: 10px; height: 10px;"></div>
<div class="return-tab" style="display: none; background: green; width: 10px; height: 10px;"></div>
<div class="analysis-tab" style="display: none; background: yellow; width: 10px; height: 10px;"></div>
</body>
</html>
最佳答案
你不需要遍历所有按钮然后绑定(bind)点击事件。您可以简单地添加点击事件处理程序并显示相关选项卡并隐藏其他选项卡。您可以尝试以下代码 -
注意::我已将tab
类添加到与选项卡相关的div 中,这样与选项卡无关的其他div 将不会受到影响。我建议您是否可以将一个包装器 div 放在选项卡 div 周围,这将使您更好地控制。
$(function(){
$("input:button").on("click", function(){
var name = $(this).attr("name");
var $tabToShow = $("div.tab." + name);
$tabToShow.show();
$("div.tab").not($tabToShow).hide();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" name="overview-tab" value="Overview">
<input type="button" name="return-tab" value="Return">
<input type="button" name="analysis-tab" value="Analysis">
<div class="overview-tab tab" style="background:red; width: 10px; height: 10px;">OverView Tab</div>
<div class="return-tab tab" style="display: none; background: green; width: 10px; height: 10px;">Return Tab</div>
<div class="analysis-tab tab" style="display: none; background: yellow; width: 10px; height: 10px;">Analysis Tab</div>
关于javascript - 隐藏 div(取决于按下的按钮),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52403485/