我目前正在通过 Wordpress 使用联系表单插件,因此输出的 HTML 和 JS 如下所示:
$('.form .form--field label').click(function() {
$(this).parents('.form--field').addClass('form--field--focus');
$('input').filter(':first').focus();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form--field form--field__firstname">
<label for="firstname" class="form--field__label">First Name</label>
<span>
<input type="text" name="firstname">
</span>
</div>
这个设计让我有点不习惯,但无论如何,我试图弄清楚如何在用户单击标签时强制将注意力集中在相应的输入上。目前,这就是我的处境。如果有人有任何意见或建议,我们将不胜感激。
最佳答案
for
<label>
上的属性寻找 id
不是 name
。下面的示例应该在没有 JavaScript 的情况下工作
<div class="form--field form--field__firstname">
<label for="firstname" class="form--field__label">First Name</label>
<span>
<input type="text" id="firstname" name="firstname">
</span>
</div>
不过,如果您确实想使用 JavaScript/JQuery 执行此操作,而不是受限于使用标签,则可以使用 $(this).next().children().focus();
来完成此操作。
$('.form--field__label').click(function() {
$(this).next().children().focus();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form--field form--field__firstname">
<label class="form--field__label">First Name</label>
<span>
<input type="text">
</span>
</div>
<div class="form--field form--field__secondname">
<!-- using a span instead of label as an example !-->
<span class="form--field__label">Second Name</span>
<span>
<input type="text">
</span>
</div>
关于javascript - 力集中于 sibling 的输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47892201/