【问题标题】:Add value to the active input field [closed]向活动输入字段添加值[关闭]
【发布时间】:2015-10-07 11:46:45
【问题描述】:

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

我使用 autofocus 属性来获取 "the_field" ,它没有返回任何内容。

【问题讨论】:

  • Questions seeking debugging help ("why isn't this code working?") must include the desired behavior, a specific problem or error and the shortest code necessary to reproduce it in the question itself. Questions without a clear problem statement are not useful to other readers.
  • 我不太确定它应该如何表现?
  • 不知道该示例案例应该做什么。无效的损坏代码不能替代正确的问题和预期的行为描述

标签: javascript jquery html selecteditem


【解决方案1】:

原版JS

首先给出你可能想要添加到某个类的所有输入,我们称之为input-field。如果您使用的是 vanilla JS,您可以像这样执行 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 是一个检查元素是否具有特定类的函数(从here 窃取):

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')) {
    ...

如果您不想添加额外的类而只是检查它是否是带有文本类型的输入,您可以像这样检查:

if(focused.tagName == 'input' && focued.getAttribute('type') == 'text') {
    ...

jQuery

或者,如果您更喜欢使用 JQuery,您可以在没有额外功能的情况下完成:

focused = jQuery(':focus');

if(focused.hasClass('input-field')) {
    focused.val(focused.val() + '3');
}

同样,如果您想跳过课程并检查输入类型的文本,只需使用以下代码:

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

另请参阅此问题:"How to get the focused element with jQuery?"

【讨论】:

  • 请注意,这不考虑光标在文本字段中的位置,它只会附加到末尾。如果这是一个问题,请告诉我,我会尝试更新我的答案。
  • 这有点老了,但你知道有Element.classList.contains()吗?你不需要实现你自己的hasClass()developer.mozilla.org/en-US/docs/Web/API/Element/classList
  • 事情永远不会变老,所以谢谢 - 会更新我的答案。我不知道。它当然更整洁,但浏览器支持不是很好。你需要 IE10。
猜你喜欢
  • 2019-05-21
  • 1970-01-01
  • 2023-03-22
  • 1970-01-01
  • 1970-01-01
  • 2016-01-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多