2010-10-12 73 views
0

有人能告訴我這是做什麼?我應該如何在我的html中引用這個?我想要的是在HTML中回顯錯誤消息。Jquery addClass問題

$('#' + $field) 
    .addClass('invalid') 
    .siblings('.error') 
     .text($message) 
     .show(); 
+0

是的,我看你想呼應的錯誤消息。但是你什麼時候想要ti?你想如何出現?哪裏? – Reigel 2010-10-12 06:51:26

+0

Reigel,我想在我的html下面的div中使用錯誤消息。 – jim 2010-10-12 07:05:49

回答

1
$('#' + $field) 
    // finding an element that has the `id` of the string/object referred to by $field 
    .addClass('invalid') 
    // adding the class-name 'invalid' to this element 
    .siblings('.error') 
     // selecting the sibling element of class-name 'error' 
     .text($message) 
     // replacing the text of that sibling, if any, with the value represented by the variable '$message' 
     .show(); 
     // showing/un-hiding that element. 

你可以通過首先分配一個元件$field,加入類名稱「錯誤」的一個元素作爲元素的兄弟,和到$message變量分配信息使用此。


編輯迴應OP的澄清請求(在評論中)。

一個相當簡單的例子:

$(document).ready(
    function(){ 
     var $field = $('input[name=fieldName]').attr('id'); 
     var error = 'This field needs something else. Such as...'; 

     $('#'+$field).addClass('invalid').siblings('.error').text($message).show(); 
    } 
); 

<form action="" method="get"> 
    <fieldset> 
     <label for="fieldName">This is a label:</label> 
     <input type="text" name="fieldName" id="fieldName" /> 

     <div class="error"></div> 
    </fieldset> 
</form> 

Rudimentary demo at JS Fiddle

+0

大衛,感謝您的幫助和解釋。我對JQ非常陌生,所以你解釋的大部分內容都沒有完成。你能告訴我如何在html中使用它嗎?像這樣?:'

' – jim 2010-10-12 06:44:22

+0

我正確地說錯誤信息會在div中回顯嗎? – jim 2010-10-12 06:46:10

+0

謝謝你的幫助,大衛。我當然可以消化這一點,並最終了解它們是如何結合在一起的。 – jim 2010-10-12 06:52:52

0

添加類名「無效」(類=「無效」),以選擇的域,然後在與類「.error」兄弟姐妹改變文本並顯示它們(刪除顯示:無)。

+0

感謝Māris,現在我只需要弄清楚如何使用它們。 :) – jim 2010-10-12 06:45:28