javascript - 隐藏 div(取决于按下的按钮)

标签 javascript jquery html

这是我在开始 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/

相关文章:

javascript - 浏览器兼容性--- 纯 Javascript 代码

javascript - 将 86.678、1.12517、0.61457 等字符串转换为数字并递增/递减最后 3 位数字

javascript - 连续返回元素的位置

html - 缩短我用于 DIV 的代码

javascript - 在 javascript 函数中进行 2 次 xmlhttp.open 调用

HTML:如何将元素宽度设置为 (a) 屏幕宽度或 (b) 以像素为单位的某个尺寸中的最小值?

javascript - AJAX 不发送变量写入 txt

javascript - 在 vue 中将链接数组从父级传递给子级(创建链接菜单)

javascript - 火狐插件 : how to debug simple-storage using addon builder

javascript - 将用户数据从 JSON 提取到展开的选择框并在选择选项时显示值