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 键吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

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

相关文档推荐

在开发JS过程中,会经常遇到两个小数相运算的情况,但是运算结果却与预期不同,调试一下发现计算结果竟然有那么长一串尾巴。如下图所示: 产生原因: JavaScript对小数运算会先转成二进制,运算完毕再转回十进制,过程中会有丢失,不过不是所有的小数间运算会
问题描述: 在javascript中引用js代码,然后导致反斜杠丢失,发现字符串中的所有\信息丢失。比如在js中引用input type=text onkeyup=value=value.replace(/[^\d]/g,) ,结果导致正则表达式中的\丢失。 问题原因: 该字符串含有\,javascript对字符串进行了转
Rails/Javascript: How to inject rails variables into (very) simple javascript(Rails/Javascript:如何将 rails 变量注入(非常)简单的 javascript)
CoffeeScript always returns in anonymous function(CoffeeScript 总是以匿名函数返回)
Ordinals in words javascript(javascript中的序数)
getFullYear returns year before on first day of year(getFullYear 在一年的第一天返回前一年)