javascript - 循环遍历 javascript 改进

标签 javascript jquery html

下面的代码工作正常,但它是硬编码的。我希望能够创建一个字段集数组,隐藏这些字段,然后每次单击“#createEventForm-eventInformation-addElement”按钮时它都会显示下一个。以下代码的问题在于它是硬编码的,因此很容易中断并且比使用循环要大得多。谁能帮我把它做得更好。

$("#fieldset-group1").hide();
$("#fieldset-group2").hide();
$("#fieldset-group3").hide();
$("#fieldset-group4").hide();
$("#fieldset-group5").hide();
$("#fieldset-group6").hide();
$("#fieldset-group7").hide();
$("#fieldset-group8").hide();
$("#fieldset-group9").hide();

$("#createEventForm-eventInformation-addElement").click( 
  function() { 
      ajaxAddEventInformation();
      if($("#fieldset-group1").is(":hidden"))
      {
          $("#fieldset-group1").show();
      }
      else
      {
          $("#fieldset-group2").show();
      }


   }
);

最佳答案

您应该使用 jquery 选择器的 ^= 表示法,这意味着开始于 ..

// this will hide all of your fieldset groups
$('[id^="fieldset-group"]').hide(); 

然后

$("#createEventForm-eventInformation-addElement").click( 
  function() { 
      ajaxAddEventInformation();
      // find the visible one (current)
      var current = $('[id^="fieldset-group"]:visible');
      // find its index
      var index = $('[id^="fieldset-group"]').index( current ); 
      // hide the current one
      current.hide(); 
      // show the next one
      $('[id^="fieldset-group"]').eq(index+1).show(); 
   }
);

关于javascript - 循环遍历 javascript 改进,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2135109/

相关文章:

javascript - 单击时获取表格行 ID

php - 如何循环$_GET获取所有数据

javascript - 如何检测与 html5 背景视频不兼容的浏览器并改为显示图像?

javascript - 数据数组中带有 php 循环的谷歌图表不显示

javascript - 加号在 Google Apps Script + MySQL 中转换为空格

javascript - 如何在 JavaScript 中从 Selenium 中具有特定类的标签获取内容

jquery - rake 中止! ExecJS::运行时错误:(execjs):1

在 chrome 中完成检查元素后,Jquery 工作

javascript - JS 将数字四舍五入到小数点后两位

javascript - 如何在下拉列表中设置默认值 javascript