5

js实现输入框赋值,实现输入框的内容通过控制台自动发送

 8 months ago
source link: https://www.80shihua.com/archives/3314
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

js实现输入框赋值,实现输入框的内容通过控制台自动发送

作者: dreamfly 分类: javascript 发布时间: 2023-11-28 12:47

在开发Web应用程序时,有时需要在控制台中模拟输入框的输入。例如,在测试表单功能时,可以使用控制台js来自动填写表单。

要通过控制台js模拟输入框的输入,可以使用以下方法:

使用keydown事件

keydown事件是键盘按下时触发的事件。可以使用keydown事件来模拟输入框中的字符输入。

function setNativeValue(element, value) {
  const valueSetter = Object.getOwnPropertyDescriptor(element, 'value').set;
  const prototype = Object.getPrototypeOf(element);
  const prototypeValueSetter = Object.getOwnPropertyDescriptor(prototype, 'value').set;

  if (valueSetter && valueSetter !== prototypeValueSetter) {
    prototypeValueSetter.call(element, value);
  } else {
    valueSetter.call(element, value);
  }
}

setNativeValue(document.getElementById('inputTextArea'),"可以帮我写一篇关于广西一男子骑电车“水上漂”的文章吗");
document.getElementById('inputTextArea').dispatchEvent(new Event('input', { bubbles: true }));

inpEle = document.getElementById('inputTextArea')

var event = document.createEvent('Event')
event.initEvent('keydown', true, false)   
event = Object.assign(event, {
  ctrlKey: false,
  metaKey: false,
  altKey: false,
  which: 13,
  keyCode: 13,
  key: 'Enter',
  code: 'Enter'
})
inpEle.focus()
inpEle.dispatchEvent(event)

setNativeValue 方法实现对输入框的赋值,dispatchEvent 实现模拟事件触发。
需要修改的就是元素ID值,或者通过document.getElementsByClassName来获取.

以上是通过控制台js模拟输入框的输入的三种方法。具体使用哪种方法取决于具体的需求。

如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK