Javascript 可以为我按 Enter 键吗?

Can Javascript press the Enter key for me?(Javascript 可以为我按 Enter 键吗?)
本文介绍了Javascript 可以为我按 Enter 键吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

有一个网站,我想在我离开时继续点击进入.有没有可能做类似的事情

There's a site that I want to continue to hit enter on while I'm away. Is it possible to do something like

setInterval(function(){
    //have javascript press the button with a certain id
},100);

我想把它放在智能搜索栏中,这样它就可以运行代码了.

I was thinking of just putting that in the smart search bar so it would run the code.

推荐答案

按下回车键会触发一个事件.您必须弄清楚他们正在听哪个事件侦听器.我将在以下示例中使用 keyup:

Well pressing enter is triggering an event. You would have to figure out which event listener they are listening to. I'll use keyup in the following example:

假设 el 是您想要输入的元素的变量.我不确定你将如何获得该元素,但我相信你知道.

Assume el is the variable for the element you want enter to be pressed on. I'm not sure how you going to get that element but I'm sure you know.

var evt = new CustomEvent('keyup');
evt.which = 13;
evt.keyCode = 13;
el.dispatchEvent(evt); //This would trigger the event listener.

没有办法真正模拟硬件动作.它只是触发事件监听器.

There's no way to actually simulate a hardware action. It just triggers the event listener.

比如调用el.click()只是调用事件监听的回调,并不是真正的按键.

For example calling el.click() is only calling the callback of the event listener, not actually pressing the key.

所以你知道当你给一个元素添加一个事件监听器时,第一个参数是 event 对象.

So you know how when you add an event listener to an element the first argument is the event object.

el.addEventListener('keyup', function(event) {
   //Do Something
});

el

如果程序员使用:

el.onkeyup = function(event) {
  //do whatever.
}

这非常简单.

只需调用 el.onkeyup(evt);

因为 onkeyup 是一个函数.

为什么我使用 CustomEvent 而不是 KeyboardEvent 因为 new KeyboardEvent('keyup') 返回的是一个具有 属性的对象keyCode 不使用 Object.definePropertyObject.defineProperties

Why did I use CustomEvent instead of KeyboardEvent because new KeyboardEvent('keyup') return's an object with the properties which and keyCode that can't be rewritten without the use of Object.defineProperty or Object.defineProperties

这篇关于Javascript 可以为我按 Enter 键吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

How do I can get a text of all the cells of the table using testcafe(如何使用 testcafe 获取表格中所有单元格的文本)
node_modules is not recognized as an internal or external command(node_modules 未被识别为内部或外部命令)
How can I create conditional test cases using Protractor?(如何使用 Protractor 创建条件测试用例?)
PhantomJS and clicking a form button(PhantomJS 并单击表单按钮)
Clicking #39;OK#39; on alert or confirm dialog through jquery/javascript?(在警报上单击“确定或通过 jquery/javascript 确认对话框?)
QunitJS-Tests don#39;t start: PhantomJS timed out, possibly due to a missing QUnit start() call(QunitJS-Tests 不启动:PhantomJS 超时,可能是由于缺少 QUnit start() 调用)