使用最接近焦点最近的文本框

Jac*_*per 2 html forms jquery focus closest

我正在尝试创建最有效的功能,在单击旁边的标签时聚焦文本框.我有一个工作函数,但它充满了一堆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>
Run Code Online (Sandbox Code Playgroud)

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();
    }
});
Run Code Online (Sandbox Code Playgroud)

现在我想创建一些更小的东西,比如:

jQuery的:

$('.signup_container .form-label').click(function() {
    $(this).closest('input[type=text]').focus();
});
Run Code Online (Sandbox Code Playgroud)

但是我无法让这个功能正常运行.是否有可能使用最接近和焦点这样的?

Igo*_*vić 10

最接近的方法返回与选择器匹配的元素的最近元素.

这是官方文档:http://api.jquery.com/closest/

一个办法

其他一些解决方案是使用两次父选择器,然后使用查找一次.当然我假设你的HTML不会改变.

$('.signup_container .form-label').click(function() {
    $(this).parent().parent().find('input[type=text]').focus();
});
Run Code Online (Sandbox Code Playgroud)

更好的解决方案

如果可以的话,做这样的事情会更好.

<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>
Run Code Online (Sandbox Code Playgroud)

然后使用最近的方法查找最接近的.inputGroup父级

$('.signup_container .form-label').click(function() {
    $(this).closest('.inputGroup').find('input[type=text]').focus();
});
Run Code Online (Sandbox Code Playgroud)