jQuery 兄弟姐妹和 $(this) 模糊和焦点
我有一个带有标签和输入字段的表单。当单击某个字段时,我想使用 CSS 设置该字段的样式,并在标签下的 div 中显示有关输入要求的一些信息。
focus() 和 Blur() 事件添加了用于设置字段样式的类,但尝试显示/隐藏信息 div 会使用 $(this).siblings() 触发所有字段上的方法
$(".input-field").focus(function() {
$(this).addClass("input-field-focus");
$(this).siblings(".label-info").show();
return false;
});
$(".input-field").blur(function() {
$(this).removeClass("input-field-focus");
$(this).siblings(".label-info").hide();
return false;
});
<label for="login">
User name:<br />
<div class="label-info">minimum 6 chararcters: letters, numbers and symbols - _ . @</div>
<input type="text" name="login" class="input-field" value="<?php echo (isset($_POST['login'])) ? $_POST['login'] : ""; ?>">
</label>
I have a form with labels and input fields. When clicking into a field I want to style the field with CSS and display some information about the input requirements in a div under the label.
The focus() and blur() events add the classes for styling the field just fine but trying to show/ hide the info divs triggers the methods on ALL fields using $(this).siblings()
$(".input-field").focus(function() {
$(this).addClass("input-field-focus");
$(this).siblings(".label-info").show();
return false;
});
$(".input-field").blur(function() {
$(this).removeClass("input-field-focus");
$(this).siblings(".label-info").hide();
return false;
});
<label for="login">
User name:<br />
<div class="label-info">minimum 6 chararcters: letters, numbers and symbols - _ . @</div>
<input type="text" name="login" class="input-field" value="<?php echo (isset($_POST['login'])) ? $_POST['login'] : ""; ?>">
</label>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
好的,现在我看到问题了。您的 HTML 标记是错误的。
label
中不能有div
元素,请使用span
代替:或者将整个块包装在自己的
div
中:否则浏览器将更正生成以下内容的标记:
因此每个
label-info
和 input 元素都将处于同一级别,因此彼此是同级元素。Ok, now I see the problem. Your HTML markup is wrong. You cannot have a
div
element insidelabel
, usespan
instead:or wrap the whole block in an own
div
:Otherwise the browser will correct the markup producing this:
So every
label-info
and input element will be on the same level and therefore siblings to each other.编辑:
根据您更新的代码,您应该使用
.prev()
而不是.siblings()
。原始答案:
您的代码工作正常:http://jsfiddle.net/D9qnk/
我的猜测是您最初隐藏了
.label-info
使用visibility: hide;
而不是display:none;
如果是这种情况,请将 css 切换为使用
display:none
。或者,如果您想使用
visibility
属性,请使用.css()
更改其值:EDIT:
Based on your updated code, you should be using
.prev()
instead of.siblings()
.Original answer:
Your code works fine: http://jsfiddle.net/D9qnk/
My guess is that your are initially hiding the
.label-info
usingvisibility: hidden;
instead ofdisplay:none;
If that's the case, switch your css to use
display:none
instead.Or if you want to use the
visibility
property, then change its value using.css()
: