Jquery addClass问题
问题描述:
有人能告诉我这是做什么?我应该如何在我的html中引用这个?我想要的是在HTML中回显错误消息。Jquery addClass问题
$('#' + $field)
.addClass('invalid')
.siblings('.error')
.text($message)
.show();
答
编辑回应OP的澄清请求(在评论中)。
$('#' + $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>
答
添加类名“无效”(类=“无效”),以选择的域,然后在与类“.error”兄弟姐妹改变文本并显示它们(删除显示:无)。
+0
感谢Māris,现在我只需要弄清楚如何使用它们。 :) – jim 2010-10-12 06:45:28
是的,我看你想呼应的错误消息。但是你什么时候想要ti?你想如何出现?哪里? – Reigel 2010-10-12 06:51:26
Reigel,我想在我的html下面的div中使用错误消息。 – jim 2010-10-12 07:05:49