如何迭代(几乎)相同类的多个div

时间:2015-12-04 09:43:49

标签: javascript jquery

假设我有12个div subClass个div,每个div都以个别号码结尾:subClass-1subClass-2等等。此外,对于每个类我都有相同的功能,例如:

function toggleAreas1() {
      var $hide = $('.toggle-areas-1 > .row:visible');      
      $hide.fadeOut(function() {
          if ($hide.next().length) {
              $hide.next().fadeIn();
          } else {
              $hide.prevAll().last().fadeIn();
          }
      });
   }

但是出于显而易见的原因,我不想使用12种不同但几乎完全相同的功能,当我轻松使用一种更通用的功能时。 我正在考虑这些方面的事情:

function toggleAreas1(index) {
   for (i = 0; i < 12; i++) { 
      index = i++
      var $hide = $('.toggle-areas-index > .row:visible');      
   }
      $hide.fadeOut(function() {
          if ($hide.next().length) {
              $hide.next().fadeIn();
          } else {
              $hide.prevAll().last().fadeIn();
          }
      });
   }

但当然它不起作用,因为我的js技能不存在。我该怎么做才能解决我的问题?

6 个答案:

答案 0 :(得分:2)

while True:
    inputfilename = input('Type the filename then press enter: ')
    try:
        inputfile  = open(inputfilename,"r", newline='')
    except FileNotFoundError:
        print ('File does not exist')
        print ('')
    else:
        break

答案 1 :(得分:0)

您可以使用字符串连接来构建jQuery选择器:

for (i = 1; i <= 12; i++) 
{ 
    var $hide = $('.toggle-areas-' + i + ' > .row:visible'); // .toggle-areas-1, .toggle-areas-2 etc.   

    $hide.fadeOut(function() {
        if ($hide.next().length) {
            $hide.next().fadeIn();
        } else {
            $hide.prevAll().last().fadeIn();
        }
    });
}

但是,为什么不给他们一个像toggle-areas这样的公共课?您可以将此类添加添加到您现有的

<div class="toggle-areas toggle-areas-1"></div>
<div class="toggle-areas toggle-areas-2"></div>
<div class="toggle-areas toggle-areas-3"></div>

然后,您将能够做到这两点:

// Affects all toogle-areas
$(".toogle-areas").fadeOut(function() {
    if ($hide.next().length) {
        $hide.next().fadeIn();
    } else {
        $hide.prevAll().last().fadeIn();
    }
});

// Affects only toogle-areas-2
$('.toggle-areas-2 > .row:first').show().nextAll().hide();

答案 2 :(得分:0)

尝试改变 var $ hide = $('。toggle-areas-index&gt; .row:visible'); 至 var $ hide = $('。toggle-areas - '+ index +'&gt; .row:visible');

答案 3 :(得分:0)

您需要使用+运算符将整数变量粘贴到字符串:

var $hide = $('.toggle-areas-' + index + ' > .row:visible');

答案 4 :(得分:0)

您要找的是attribute substring selectors

因此,如果您的课程以subClass开头,请使用:[class^=subClass]

$('[class^=subClass]');

请注意,这会针对完整属性字符串进行测试,因此如果前面还有其他内容则不匹配,即class="class1 subClass-1"在这种情况下您可以使用其他两个$=,{{1选择器。第一个以匹配结束,第二个包含匹配。

*=
jQuery('[class^=subClass]').css({
   background:'#ffff00',  
});
[class^=subClass] {
  width:48px;
  height:48px;
  margin-bottom:3px;
}

答案 5 :(得分:0)

试试这个:

rowCount()