2010-10-12 68 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