jQuery触发器事件在循环中多次

时间:2022-10-24 23:58:21

I'll start with some context: I wrote a little typing app that displays text on the screen and tracks your wpm as you type using the keypress event. Out of boredom I wanted to play around with it a little bit and have a way that it would auto type after typing a hidden command (shortend kontra code using just the arrow keys). So I have a array of characters that I am iterating through and attempting to simulate the keypress event in my each loop as shown below.

我将从一些上下文开始:我写了一个小的打字应用程序,它在屏幕上显示文本,并在您使用按键事件键入时跟踪您的wpm。出于无聊,我想稍微玩一下它并且有一种方法可以在键入隐藏命令后自动输入(仅使用箭头键缩短kontra代码)。所以我有一个字符数组,我正在迭代并尝试模拟我的每个循环中的按键事件,如下所示。

$.each(_arrToCopy, function (index, value) {
        setTimeout(function () {
          console.log(value);

          jQuery.event.trigger({ type: 'keypress', which: value.charCodeAt(0) });

          //typeIt(value);
        }, time);
        time += 500;
      });

The issue I'm having is it appears that my event is only triggering one time and then not triggering again. The setTimeout function was an early attempt to slow the loop down in case I was just processing things too quickly. After that didn't work I implemented a nearly pure javascript function (the typeIt()) function to fake the keyboard event. It is below.

我遇到的问题是,我的事件似乎只触发了一次,然后再没有触发。 setTimeout函数是一个早期尝试减慢循环,以防我只是处理太快。之后没有用,我实现了一个几乎纯粹的javascript函数(typeIt())函数来伪造键盘事件。它在下面。

function typeIt(character) {
  var keyboardEvent = document.createEvent("KeyboardEvent");
  var initMethod = typeof keyboardEvent.initKeyboardEvent !== 'undefined' ? "initKeyboardEvent" : "initKeyEvent";
  console.log(String.fromCharCode(character.charCodeAt(0)) + ' ' + (character.charCodeAt(0)));

  keyboardEvent[initMethod](
                     "keypress", // event type : keydown, keyup, keypress
                      true, // bubbles
                      true, // cancelable
                      window, // viewArg: should be window
                      false, // ctrlKeyArg
                      false, // altKeyArg
                      false, // shiftKeyArg
                      false, // metaKeyArg
                      0, // keyCodeArg 
                      character.charCodeAt(0) // charCodeArgs 
  );
  document.dispatchEvent(keyboardEvent);
}

This also typed once, but it appears to be typing the wrong character. So I circled back to trying to make the jQuery trigger work and have gotten stuck on that. I can get it to type the first letter, but after that it appears to completely stop firing. I was wondering if there's potentially a way to reset the event trigger if it's only able to fire once in the loop without being reset, or if that's even the issue here.

这也输入了一次,但似乎输入了错误的字符。所以我回过头来试图让jQuery触发器工作,并且已经陷入困境。我可以让它输入第一个字母,但之后它似乎完全停止了。我想知道是否有可能重置事件触发器的方法,如果它只能在循环中触发一次而不重置,或者这甚至是问题。

If for the sake of more context you want to take a look at what this is going in, I have a mock up here (although what I'm actually working on is now a bit more refined c# app will a full backend): http://codepen.io/jiggawagga/pen/wBoaRY

如果为了更多的上下文你想看一下这是什么,我在这里有一个模拟(虽然我实际上正在研究的是现在更精致的c#app将是一个完整的后端):http ://codepen.io/jiggawagga/pen/wBoaRY

Thanks in advance team *

在此先感谢团队*

2 个解决方案

#1


0  

I had this issue in simple jQuery click event. I did below and it worked fine. See if it solves your issue

我在简单的jQuery点击事件中遇到了这个问题。我在下面做了,它工作得很好。看看它是否解决了您的问题

jQuery(document).off().on('click', '.my-div', function(){
     // SOME EVENT GOES HERE
})

Refer http://api.jquery.com/off/

#2


0  

I copied your code into a jsfiddle to try it out. The only thing I had to change to get it to work was changing this:

我将你的代码复制到一个jsfiddle来试试。为了让它发挥作用,我唯一需要改变的是改变这个:

jQuery.event.trigger({ type: 'keypress', which: value.charCodeAt(0) });

to this:

$('#out').trigger({ type: 'keypress', which: value.charCodeAt(0)});

Basically triggering the event on the element that is to receive it. I'm not very well versed in jQuery so this might not be the solution you're after. But it worked for me.

基本上在要接收它的元素上触发事件。我不是很精通jQuery,所以这可能不是你想要的解决方案。但它对我有用。

The full js for the fiddle:

小提琴的完整js:

var _arrToCopy = Array.prototype.slice.call("lorem ipsum");
var time = 0;
$('#out').keypress(function(e){
    $(this).text($(this).text() + String.fromCharCode(e.which));
});

$.each(_arrToCopy, function (index, value) {
    setTimeout(function () {
    console.log(value);
    $('#out').trigger({ type: 'keypress', which: value.charCodeAt(0)});
  }, time);
  time += 500;
});

And the HTML:

和HTML:

<p id="out">

#1


0  

I had this issue in simple jQuery click event. I did below and it worked fine. See if it solves your issue

我在简单的jQuery点击事件中遇到了这个问题。我在下面做了,它工作得很好。看看它是否解决了您的问题

jQuery(document).off().on('click', '.my-div', function(){
     // SOME EVENT GOES HERE
})

Refer http://api.jquery.com/off/

#2


0  

I copied your code into a jsfiddle to try it out. The only thing I had to change to get it to work was changing this:

我将你的代码复制到一个jsfiddle来试试。为了让它发挥作用,我唯一需要改变的是改变这个:

jQuery.event.trigger({ type: 'keypress', which: value.charCodeAt(0) });

to this:

$('#out').trigger({ type: 'keypress', which: value.charCodeAt(0)});

Basically triggering the event on the element that is to receive it. I'm not very well versed in jQuery so this might not be the solution you're after. But it worked for me.

基本上在要接收它的元素上触发事件。我不是很精通jQuery,所以这可能不是你想要的解决方案。但它对我有用。

The full js for the fiddle:

小提琴的完整js:

var _arrToCopy = Array.prototype.slice.call("lorem ipsum");
var time = 0;
$('#out').keypress(function(e){
    $(this).text($(this).text() + String.fromCharCode(e.which));
});

$.each(_arrToCopy, function (index, value) {
    setTimeout(function () {
    console.log(value);
    $('#out').trigger({ type: 'keypress', which: value.charCodeAt(0)});
  }, time);
  time += 500;
});

And the HTML:

和HTML:

<p id="out">