2013-12-09 84 views
0

我有两个类,如下:
--- CSS:

.shw-intro { 
    width: 250px; 
    height: 150px; 
    background: rgb(95, 190, 0); 
    position: absolute; 
    top: 25px; 
    left: 50px; 
} 
.shw-intro-content { 
    display: none; 
} 

--- HTML:

<div class="shw-intro"> 
    <div class="shw-intro-content">hello</div> 
    <div class="shw-intro-content">everyone</div> 
    <div class="shw-intro-content">have fun</div> 
</div> 

在javascript中我试图做一些动画,但我两种情况之间惊讶:

var currentShw = 0; 

情况1:

function shwAnimation() { 
      if ($('.shw-intro').attr('class').indexOf('shw-intro-translate') != -1) { 
       $('.shw-intro').removeClass('shw-intro-translate'); 
       currentShw = currentShw >= $('.shw-intro-content').length ? 0 : currentShw + 1; 
      } 
      else { 
       $('.shw-intro').children().eq(currentShw).show(); // It works fine 
       $('.shw-intro').addClass('shw-intro-translate'); 
      } 
     } 

情况2:

function shwAnimation() { 
     if ($('.shw-intro').attr('class').indexOf('shw-intro-translate') != -1) { 
      $('.shw-intro').removeClass('shw-intro-translate'); 
      currentShw = currentShw >= $('.shw-intro-content').length ? 0 : currentShw + 1; 
     } 
     else { 
      $('.shw-intro').children('shw-intro-content').eq(currentShw).show(); // It doesn't work 
      $('.shw-intro').addClass('shw-intro-translate'); 
     } 
    } 
+0

有什么惊喜? – Mikhail

+0

情况2不起作用 – HICURIN

+3

'shw-intro-content'查找标记名称为'的元素。你忘了在它前面添加'.',使它成为一个类选择器。 – Blender

回答

3

当你传递一个字符串children,它过滤基于这样选择的结果。

所以

.children('.shw-intro-content') 

将只返回儿童有该类

这就是说,你有什么

.children('shw-intro-content') 

是不是真的有效的选择 是与我认为不存在的shw-intro-content类型的标签相匹配的选择器,它可能是为什么它不起作用;它会导致没有返回。

你忘了这个点吗?

+0

找到一个ID感谢你的回答,Adam Rackis先生!在我第一次尝试时,我认为它不需要点(。)。但现在我只是试图添加一个点(。),它对我来说工作正常。那么让我问你一个问题?如果我使用.children('shw-intro-content'),怎么回事?它是如何工作的?它叫什么?谢谢。 – HICURIN

+0

它的工作原理与其他jQuery选择器工作方式相同,“X”表示X类型的标签,“.X”表示X的css类,等等 –

+0

Nit:'shw-intro-content' *是一个有效的选择器..它只是不匹配,因为没有这样一个名称的元素。但是,请考虑:'document.createElement(“shw-intro-content”)'。 – user2864740

2

您应该使用CSS选择器作为.children()的参数。

像这样:$('.shw-intro').children('.shw-intro-content')

2

这应该工作

function shwAnimation() { 
if ($('.shw-intro').attr('class').indexOf('shw-intro-translate') != -1) { 
    $('.shw-intro').removeClass('shw-intro-translate'); 
    currentShw = currentShw >= $('.shw-intro-content').length ? 0 : currentShw + 1; } 
    else { 
     $('.shw-intro').children('.shw-intro-content').eq(currentShw).show(); 
     $('.shw-intro').addClass('shw-intro-translate'); 
    } 
} 

你必须USNG使用类选择 “”