简体   繁体   English

在jQuery中添加和删除类

[英]Adding and removing classes in jQuery

I have a jQuery snippet written where if any of my inputs in a specific table are entered it changes the class of the rest of the inputs on that table, but if the user fills in an input field, and then deletes their input it still changes the class, though it shouldnt. 我写了一个jQuery片段,如果输入了我在特定表中的任何输入,它将更改该表上其余输入的类,但是如果用户填写了输入字段,然后删除了他们的输入,它仍然会更改该类,尽管它不应该。 here is my attempt at doing this. 这是我的尝试。

 $('#lostTable :input').change(function(){                                          

        var $lostTableInput = $('#lostTable :input:not(input[type=hidden])');
        var hasData = false;

        $lostTableInput.each(function(){
            if($(this).val().length > 0){
                hasDataLf = true;
                return false;
            }
        });

    $lostTableInput.toggleClass('R', hasDataLf); 

// this above part works for changing the class, and below is my attempt at changing
// it back if the user deletes the data that was entered in.

    $lostTableInput.each(function(){
      if($(this).val().length == 0) {
        $lostTableInput.removeClass('R'); 
    }
   }
  )
 }
);

You could simplify a bit... 您可以简化一下...

var $inputs =  $('#lostTable :input').not(':hidden');
$inputs.change(function(){
  $(this).toggleClass('dummy', $(this).val().length > 0);
  $inputs.toggleClass('R', $inputs.filter('.dummy').length > 0);
});

You may want to look into the delegate jquery method, for better performance. 您可能需要研究委托 jquery方法,以获得更好的性能。 And you may want a better name than 'dummy' for the dummy class ;) 对于虚拟类,您可能想要一个比“ dummy”更好的名称;)

There is no reason to go through all the values. 没有理由遍历所有值。 You are looking on change of one input: 您正在寻找一种输入的更改:

$('#lostTable input').change(function() {
    var $lostTableInput = $('#lostTable input').not(':hidden');
    if (this.value.length > 0) {
        $lostTableInput.toggleClass('R', true);
    }
    else if (this.value.length == 0 || this.value == null) {
        var found_one = false;
        $lostTableInput.each(function(index, item) {
            if (item.value.length > 0) {
                found_one = true;
                return false;
            }
        })
        if (!found_one) {
            $lostTableInput.removeClass('R');
        }
    }
})

Fiddle: http://jsfiddle.net/nYrqx/ 小提琴: http//jsfiddle.net/nYrqx/

why don't you do: 你为什么不这样做:

if(!hasDataLf){ // if every field is empty this should have remained false
   $lostTableInput.removeClass('R'); 
}

可能是比较器,请尝试:

if ($(this).val() == null) { $lostTableInput.removeClass('R'); }

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

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