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

 haiziqian_486_834 发布于 2023-02-07 22:43

我正在尝试创建最有效的功能,在单击旁边的标签时聚焦文本框.我有一个工作函数,但它充满了一堆if语句.这种形式有16个文本框,所以我不希望每次单击标签时该函数都要经过16个if语句.这是我的工作代码:

HTML

        
Contact Name
Email Address

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();
});

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

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

    这是官方文档: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>
    

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

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

    2023-02-07 22:56 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有