$ .children()vs $ .children('className')有什么区别?

时间:2013-12-09 04:35:23

标签: javascript jquery html css

我有两节课如下:
--- 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');
        }
    }

3 个答案:

答案 0 :(得分:3)

将字符串传递给children时,会根据该选择器过滤结果。

所以

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

只会返回具有该类

的儿童

那说,你有什么

.children('shw-intro-content')

实际上并不是一个有效的选择器是一个选择器,它将匹配{I}类型的标签,我认为它不存在,这可能就是为什么它不起作用;它将导致没有任何返回。

你忘记了点吗?

答案 1 :(得分:2)

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

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

答案 2 :(得分: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');
    }
}

你必须通过“。”来使用类选择器。