jQuery:获取扩展某个类的css类的元素

时间:2013-02-25 19:07:28

标签: jquery css

我在css中有一个用于输入文本的类。我还有两个课程从第一课开始,如下所示:

    .input-text-parent {
         background-color: gray;
    }

    .input-text-child-1 {
         extends: input-text-parent;
         background-image: url(images/image1.jpg);
    }

    .input-text-child-2 {
         extends: input-text-parent;
         background-image: url(images/image2.jpg);
    }

现在,我想要做的是用jQuery选择扩展第一个类的所有元素(在本例中为input-text-parent)。 我知道用$(“。class”)我可以获得该类的所有元素,但我不知道如何获取它的所有子类。

非常感谢你。

我希望我的解释清楚。

2 个答案:

答案 0 :(得分:1)

我建议重构你的css,为复杂的元素使用两个类而不是另一个扩展另一个的类,除了不需要预处理之外,它们完全相同。例如:

.input-text {
     background-color: gray;
}

.input-text.child-1 {
     background-image: url(images/image1.jpg);
}

.input-text.child-2 {
     background-image: url(images/image2.jpg);
}

然后您可以使用以下标记:

<div class="input-text"></div>
<div class="input-text child-1"></div>
<div class="input-text child-2"></div>

以下javascript通过jQuery:

$(".input-text").stuff(); //Select all of them
$(".input-text.child-1").stuff(); //Select only child-1

等。

答案 1 :(得分:0)

jQuery没有专门为此构建的内容,因为css实际上没有子类支持。每个“子类”实际上只是完全独立的类,恰好具有相似的名称。

jQuery的filter方法与className属性相结合,应该能够选择类input-text-child-n

的元素
$("input").filter(function(){
    return this.className.indexOf("input-text-child-") >= 0;
}).doSomething();
相关问题