向活动输入字段添加值

Add value to the active input field

本文关键字:添加 字段 输入 活动      更新时间:2023-09-26

如何在所有input字段中为活动输入字段添加值?

我使用autofocus属性来获得"the_field",它没有返回任何东西。

Vanilla JS

首先给出所有你可能想要添加的东西到某个类的输入,我们称之为input-field。如果你使用的是普通JS,你可以这样做:

//Get the focused element.
var focused = document.activeElement;
//Check that it is one of the elements you want to add stuff to.
if(hasClass(focused, 'input-field')) {
    //Add whatever you want to add, lets say a number "3".
    focused.value = focused.value + '3';
}

其中hasClass是检查元素是否具有特定类的函数(从这里偷来的):

hasClass(el, cls) {
    if (!el.className) {
        return false;
    } else {
        var newElementClass = ' ' + el.className + ' ';
        var newClassName = ' ' + cls + ' ';
        return newElementClass.indexOf(newClassName) !== -1;
    }
}

或者(正如Edwin Reynoso指出的),如果你对你的代码不支持在IE版本10以下,你可以使用classList.contains():

if(focused.classList.contains('input-field')) {
    ...

如果你不想添加额外的类,只检查它是否是text类型的输入,你可以这样检查:

if(focused.tagName == 'input' && focued.getAttribute('type') == 'text') {
    ...
<标题> jQuery h1> 者,如果你喜欢使用JQuery,你可以做到这一点,而不需要额外的函数:
focused = jQuery(':focus');
if(focused.hasClass('input-field')) {
    focused.val(focused.val() + '3');
}

同样,如果您想跳过类并检查输入类型为text,只需使用以下命令:

if(focused.is('input[type=text]')) {
    ...

参见这个问题:"如何使用jQuery获得焦点元素?"