简体   繁体   English

jQuery-有条件地循环访问元素到addClass()

[英]JQuery - iterate through elements conditionally to addClass()

I have a few input fields that I'm trying to add a class to their parent container if they are not empty. 我有一些输入字段,如果它们不为空,我试图将一个类添加到其父容器中。

Here's the CoffeeScript: 这是CoffeeScript:

$(".inputA, .inputB").parent().addClass(->
        if !$(this).is(":empty")
            "input-set"
    )

This is successfully appending "input-set" to the parent class, but in all cases, not just empty input fields. 这可以成功地将"input-set"附加到父类,但是在所有情况下,不仅是空的输入字段。

:( :(

:empty will select elements that don't have children. :empty将选择没有子元素的元素。 Therefore, using it to conditionally select the parents of certain elements doesn't make any sense. 因此,使用它有条件地选择某些元素的父元素没有任何意义。

ref: https://developer.mozilla.org/en-US/docs/Web/CSS/:empty 参考: https : //developer.mozilla.org/en-US/docs/Web/CSS/ : empty

If you're looking to add the class to the parents of inputs that haven't been populated then you could use something like: 如果您要将该类添加到尚未填充的输入的父类中,则可以使用以下方法:

$(".inputA, .inputB").each(function(){
    if (this.value !== "") {
        $(this).parent().addClass('input-set');
    }
});

Use jQuery.filter() 使用jQuery.filter()

$(".inputA, .inputB").filter(function(){
    return this.value !='';
}).parent().addClass("input-set");

Less function calls than using $.each 比使用$.each更少的函数调用

First, input elements are by definition empty.. 首先,根据定义, input元素为空。

Read the :empty documentation at http://api.jquery.com/empty-selector/ 阅读http://api.jquery.com/empty-selector/上:empty文档

Second you are testing the parent elements and not the input ones.. ( and since they are parents, meaning they are not empty they all fit the bill.. ) 其次,您正在测试父元素,而不是input元素。.( 由于它们是父元素,这意味着它们并不为空,因此它们都符合要求。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM