我正在尝试创建最有效的函数来在单击文本框旁边的标签时聚焦文本框。我有一个工作函数,但它充满了一堆 if 语句。这种形式有 16 个文本框,所以我不希望每次单击标签时函数都必须经过 16 个 if 语句。这是我的工作代码:
HTML
<div>
<div>
<span class="form-label">Contact Name</span>
</div>
<div>
<input type="text" name="name" id="signup_name">
</div>
</div>
<div>
<div>
<span class="form-label">Email Address</span>
</div>
<div>
<input type="email" name="email" id="signup_email">
</div>
</div>
jQuery
$('.signup_container .form-label').click(function() {
labelName = $(this).html()
if (labelName.indexOf("Contact Name") >= 0) {
$('#signup_name').focus();
}
if (labelName.indexOf("Email Address") >= 0) {
$('#signup_email').focus();
}
});
现在我想创建一些像这样更小的东西:
jQuery:
$('.signup_container .form-label').click(function() {
$(this).closest('input[type=text]').focus();
});
但是我无法让这个函数正常执行。是否可以像这样使用 closest 和 focus?
最佳答案
最近的方法返回与选择器匹配的元素的最近父级。
这是官方文档:http://api.jquery.com/closest/
解决方案
其他一些解决方案是使用两次父选择器,然后使用查找选择器。当然,我假设您的 html 不会更改。
$('.signup_container .form-label').click(function() {
$(this).parent().parent().find('input[type=text]').focus();
});
更好的解决方案
如果可以的话,做这样的事情会更好。
<div class='inputGroup'>
<div>
<span class="form-label">Contact Name</span>
</div>
<div>
<input type="text" name="name" id="signup_name">
</div>
</div>
<div class='inputGroup'>
<div>
<span class="form-label">Email Address</span>
</div>
<div>
<input type="email" name="email" id="signup_email">
</div>
</div>
然后使用closest方法找到最近的.inputGroup parent
$('.signup_container .form-label').click(function() {
$(this).closest('.inputGroup').find('input[type=text]').focus();
});
关于jquery - 使用最接近焦点的最接近文本框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20793587/