强制关注同级输入 [英] Force Focusing on Sibling Input
问题描述
我目前正在通过Wordpress使用联系人表单插件,因此输出的HTML和JS如下所示:
I'm currently working with a contact form plugin through Wordpress and so the outputted HTML and JS looks like the following:
$('.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>
该设计使我对它有点不了解,但是无论如何,我试图弄清楚每当用户单击标签时如何强制将注意力集中在相应的输入上.目前,这就是我的想法.如果有人有任何意见或建议,将不胜感激.
The design has caused me to get a bit hacky with it but in any event, I'm trying to figure out how to force focus on the respective input whenever the user clicks on a label. At the moment, this is where I'm at with it. If anyone has any input or suggestions, that would be greatly appreciated.
推荐答案
<label>
上的for
属性查找id
不是的name
.下面的示例在没有JavaScript的情况下应该可以工作
the for
attribute on a <label>
looks for an id
not a name
. Example below should work without 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();
Although if you really want to do this with JavaScript/JQuery and not be tied down to using a label you can do it this way using $(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>
这篇关于强制关注同级输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!