2011-05-19 123 views
-1

我有一個jQuery代碼片段,其中如果輸入了特定表中的任何輸入,它將更改該表中其餘輸入的類,但是如果用戶填入輸入字段,然後刪除他們的輸入它仍然改變類,但它不應該。這是我的嘗試。在jQuery中添加和刪除類

$('#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'); 
    } 
    } 
) 
} 
); 
+0

你聲明變量爲「hasData」,但你實際上使用了「hasDataLf」......這應該是什麼? – Pointy 2011-05-19 14:03:21

+0

所以當任何''變化時,你會發現所有的輸入,並且如果它們中的任何一個具有非空值,則將類「R」添加到它們中的全部。然後,您想要從任何空白的課程中刪除「R」。似乎你可以做到這一點更簡單... – Pointy 2011-05-19 14:05:38

+0

我改變了我的答案 – Neal 2011-05-19 14:08:30

回答

3

你可以簡化有點...

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

你可能要考慮的delegate jQuery的方法,對更好的性能。你可能想要一個比'dummy'更好的虛擬類的名字;)

+0

是的,我也試過,但OP只想刪除類如果在任何「輸入」 – Neal 2011-05-19 14:09:24

+0

中都有** no **輸入,以便將其考慮在內。謝謝@Neal。 – sje397 2011-05-19 14:18:01

+0

...再次。 Soz :) – sje397 2011-05-19 14:23:38

0

你爲什麼不這樣做:

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

這樣做是有道理的,但當我嘗試它時,它不起作用。這就像輸入字段仍然認爲他們的字段中有數據。 – Dan 2011-05-19 14:04:28

0

可能是比較,嘗試:

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

1

沒有理由要經過所有的值。您正在尋找一個輸入上的變化:

$('#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'); 
     } 
    } 
}) 

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

+0

嗯...除非我複製不正確,我無法得到這個工作。當我輸入特定的輸入字段時,它沒有切換類。 – Dan 2011-05-19 14:16:32

+0

'.change'正在退出。嘗試使用'keyup'而不是'change' – Neal 2011-05-19 14:22:04

+0

這裏是'keyup':http://jsfiddle.net/nYrqx/1/ – Neal 2011-05-19 14:23:51