您好,我有一个输入表单,还有一些标签可以帮助用户填写表单。我的CSS默认设置为隐藏这些,但是当用户单击输入字段上的焦点时,下一个标签将显示,并且模糊时它将被隐藏。
由于某种原因,我编写的当前脚本会不断显示所有标签,并且似乎不会在模糊时隐藏它。
不是 jQuery 专家,所以如果有人能帮助我解决这个问题那就太好了。
我的代码在下面或查看 jsFiddle :
js/js.js
$(document).ready(function(){
$('.form-control').bind('blur', function(){
$('.form_helper').removeClass("form_helper_show").addClass('.form_helper'); });
$('.form-control').bind('focus', function(){
$('.form_helper').removeClass("form_helper").addClass('form_helper_show'); });
});
css/style.css
ul {
list-style:none;
}
li:nth-child(2), li:nth-child(3) {
display:inline;
}
.form_helper {
display:none;
}
.form_helper_show {
display:inline-block;
}
index.html
<div class="form-group">
<ul class="form_group">
<li><label for="client_name">Company Name</label></li>
<li><input class="form-control" name="client_name" type="text" id="client_name"/></li>
<li><label for="client_name_helper" class="form_helper">Input your clients name</label></li>
</ul>
</div>
<div class="form-group">
<ul class="form_group">
<li><label for="client_name">Company Code</label></li>
<li><input class="form-control" name="client_name" type="text" id="client_name"/></li>
<li><label for="client_name_helper" class="form_helper">Input your clients code</label></li>
</ul>
</div>
最佳答案
尝试
$(document).ready(function () {
$('.form-control').bind('blur', function () {
$(this).parent().next('li').find('.form_helper_show').removeClass("form_helper_show").addClass('form_helper');
});
$('.form-control').bind('focus', function () {
$(this).parent().next('li').find('.form_helper').removeClass("form_helper").addClass('form_helper_show');
});
});
<小时/>
更好的方法
$(document).ready(function () {
$('.form-control').bind('blur', function () {
$(this).parent().next('li').find('.form_helper').hide();
}).bind('focus', function () {
$(this).parent().next('li').find('.form_helper').show();
});
});
<小时/>
更好用.on()而不是.bind()
<小时/> 引用文献As of jQuery 1.7, the .on() method is the preferred method for attaching event handlers to a document. For earlier versions, the .bind() method is used for attaching an event handler directly to elements. Handlers are attached to the currently selected elements in the jQuery object, so those elements must exist at the point the call to .bind() occurs. For more flexible event binding, see the discussion of event delegation in .on() or .delegate().
关于jQuery 在输入表单上绑定(bind)焦点和模糊事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20017300/