JavaScript 更有效的代码来隐藏除衣柜之外的所有元素

标签 javascript jquery html

我有大约 20 张表格。当 A 按钮时,关闭表单应取消隐藏。

所有其他形式都应保持隐藏。 '

我就是这样做的

$(document).ready(function() {
    console.log( "ready!" );

      $(".toggle-new-form1").click(function() {
    $(".new-form1").toggleClass("hidden");
    // $("input[name='union_name']").focus();
  });
      $(".toggle-new-form2").click(function() {
    $(".new-form2").toggleClass("hidden");
    // $("input[name='union_name']").focus();
  });


});

这是 html 示例

    <div class="form-group" style="">
    <label >Email:</label>
    <button type="button" id="new" style="margin-top:7px;"  class="toggle-new-form pull-right btn btn-primary">Edit</button>
    <p> example@gmail.com  </p>
    </div>
    <form  id="name-form" class="new-form1 hidden" method="POST"  action="">
    <input id="email">
<button type="submit"> Submit </button> 
    </form>

但我无法隐藏以前激活的表单。

是否有办法提高效率并隐藏以前激活的表单。

我也尝试过

<script type="text/javascript">

$(document).ready(function() {
    console.log( "ready!" );

      $(".toggle-new-form").click(function() {
    $(".new-form").addClass("hidden");
     $(this).closest( ".new-form" ).removeClass( "hidden" )
  });


});
</script>

我不知道它是如何工作的

Js fiddle https://jsfiddle.net/0p2brLww/2/

最佳答案

您可以尝试对所有按钮+表单执行这样的单击事件

$(document).ready(function() {
      $('[class^="toggle-new-form"]').click(function() {
       var el = $(this).parent().next();
           $('[class^="new-form"]').not(el).addClass('hidden');
           el.toggleClass("hidden");
     //$(this).parent().next().find("input[name='union_name']").focus();
  });

});

关于JavaScript 更有效的代码来隐藏除衣柜之外的所有元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39504431/

相关文章:

javascript - 从 shadowbox 中拉取表单,并从父窗口提交

html - flex 盒内部无法与带有伪元素的标签在末尾对齐

html - 将文本限制为 X 行,但调整宽度以显示所有内容

javascript - 获取应用于特定元素的所有 css 样式的列表

javascript - 单击单元格外部后如何退出文本框

javascript - jquery 正斜杠转义

html - 图像上的半透明颜色层?

javascript - 基于数组按 ids 组织列表 - jQuery/JS

javascript - 提交不适用于 IE

javascript - jQuery - 在选择更改时清除文本区域