2017-06-05 55 views
2

我想創建一個基於驗證的自定義錯誤消息和樣式(我知道關於插件,但涉及協調驗證插件與Materialise的時間太多,單個字段)。不能設置未定義的屬性'顏色'

HTML:

<div class="input-field inline center-align"> 
    <input id="quantity" name="quantity" type="number" class=""> 
    <label for="qty" data-error="wrong" data-success="right" 
     class="active">Qty</label> 
    <span id="qty-error">really?</span> 
</div> 

JS:

$('#quantity').change(function(){ 
    var $Qty = $(this).val(); 
    var $Label = $('#qty-error'); 
    if ($Qty > 0 && $Qty <= $AvailTix){ 
     $Label.html('seems reasonable'); 
     $Label.style.color = '#8e8ef5'; 
     $(this).addClass('valid'); 
    } else if ($Qty < 1){ 
     $Label.html('really?'); 
     $Label.style.color ='#f96d63'; 
     $(this).addClass('invalid'); 
    } 
}); 

什麼是困惑我的是,$Label.html件工作。它改變了文字。但我在控制檯中此錯誤的$Label.style.color行:

Uncaught TypeError: Cannot set property 'color' of undefined

回答

1

.style是財產一個元素。有了jQuery,你可以在數組中找到這個元素。更像是[elem]。所以,使用:

$Label.css('color', '#f96d63'); 

$Label.get(0).style.color = '#8e8ef5'; 

但第一個是更jQueryish

0

$Label是一個jQuery對象,而不是一個標準的節點元素,這樣你就可以做$Label[0].style.color = '#8e8ef5';$Label.css('color', '#8e8ef5');

0

嘗試$Label.css({color:'#8e8ef5'});

0

你的問題是,你正在嘗試一個jQuery對象訪問DOM屬性style,這就是爲什麼你有Cannot set property 'color' of undefined

在您的代碼中$Label是一個jQuery對象,並且沒有style屬性,因爲.style是DOM對象屬性,因此您不能將它用於jQuery對象。

您需要使用.css()方法代替:

$Label.css('color', '#8e8ef5'); 

欲瞭解更多詳情,您可以閱讀jQuery object and DOM element

相關問題