2012-06-29 74 views
0

我使用下面的函數進行驗證:發現哪一類引發模糊

//Validation 
$('.sValidate').bind('blur', function() { 
    if (!$(this).val()) { 
     $(this).removeClass('short_input'); 
     $(this).addClass('short_input_negative'); 
     return false; 
    } 
}); 

我的大部分輸入類是short_input。但其中一些也被命名爲long_input
我如何知道input觸發blur的級別,刪除它並添加long_input_negative

<input type="text" id="loginname" name="loginname" class="short_input sValidate" value="JDoe"> 
+0

一個類不能觸發事件 – Alp

+0

@Alp這是可能的結合由jQuery選擇返回的任何元素。更多信息:http://api.jquery.com/bind/ –

回答

6

可以使用.hasClass()方法類檢測:

$('.sValidate').bind('blur',function(){ 
    if (!$(this).val()){ 
     if($(this).hasClass('long_input')) { 
      $(this) 
        .removeClass('short_input'); 
        .addClass('short_input_negative'); 
     } 

     if($(this).hasClass('short_input')) { 
      $(this) 
       .removeClass('long_input'); 
       .addClass('long_input_negative'); 
     } 
    } 
}); 

從jQuery的文檔有關.hasClass()

確定是否有任何匹配的元素被分配給定的 類。

的另一種方法是使用.is()

$('.sValidate').bind('blur',function(){ 
    if (!$(this).val()){ 
     if($(this).is('.long_input')) { 
      // do something of long_input 
     } 

     if($(this).is('.short_input')) { 
      // do something of short_input 
     } 
    } 
}); 

從jQuery的文檔有關.is()

檢查當前匹配組針對一個選擇器,元件元件, 或jQuery對象並且如果這些元素中的至少一個爲 ,則返回true克服給定的論點。

0

雖然@thecodeparadox回答了您的原始問題,但我想指出「您做錯了」 - 不知道您的課程實際上做了什麼。我猜foo_negative班應該把顏色切換成紅色或類似的東西。

.short_input { 
    width: 50px; 
} 

.long_input { 
    width: 100px; 
} 

.negative { 
    color: red; 
} 

現在,可以讓你保持short_inputlong_input類和簡單的添加/刪除negative類來改變你的造型。如果你不知道這一點,看看MDN CSS

0

這裏這條線!$(this).val()返回false,如果有一些值。所以條件從不執行。

做到這一點的方法: -

$('.sValidate').bind('blur',function(){ 
    if ($(this).val().length > 0){ 
     if ($(this).hasClass('short_input')) { 
      $(this).removeClass('short_input'); 
      $(this).addClass('short_input_negative'); 
     } 
     if ($(this).hasClass('long_input')) { 
      $(this).removeClass('long_input'); 
      $(this).addClass('long_input_negative'); 
     } 
    } 
});​ 

參考LIVE DEMO