简体   繁体   English

使用纯 JS(不是 jQuery)将事件监听器添加到多个输入元素

[英]Adding event listeners to multiple input elements using plain JS (not jQuery)

I have a code block that works perfectly in jQuery but it's the last bit of a project I am converting to plain vanilla Javascript with the specific aim to remove any and all dependencies on jQuery.我有一个在 jQuery 中完美运行的代码块,但它是我正在转换为普通香草 Javascript 的项目的最后一部分,其特定目的是删除对 jQuery 的任何和所有依赖项。

Here is the existing code block at issue:这是有问题的现有代码块:

$("input[data-pattern='comma']").on({
    keyup: function() {inputComma($(this));}
});

How do I achieve this same functionality using ONLY plain pure JS?如何仅使用普通的纯 JS 实现相同的功能?

Note: inputComma is a custom handler that conforms the value for EACH input element instance to a comma-delimited regex pattern as the user is typing.注意: inputComma 是一个自定义处理程序,它在用户键入时使每个输入元素实例的值符合以逗号分隔的正则表达式模式。

If it helps, I tried...如果有帮助,我试过...

document.querySelectorAll("input[data-pattern='comma']").forEach(function(elem) {
    elem.addEventListener("keyup", function() {inputComma(elem);});
});

and also...并且...

document.querySelectorAll("input[data-pattern='comma']").forEach(function(elem) {
    elem.addEventListener("keyup", () => {inputComma(elem);});
});

I know jQuery's $(this) is different from "this" and that arrow functions also materially affect which "this" is being referenced.我知道 jQuery 的 $(this) 与“this”不同,箭头函数也会对引用哪个“this”产生重大影响。 I tried to get around that issue by referencing the iterating object but I think that may be part of my problem.我试图通过引用迭代 object 来解决这个问题,但我认为这可能是我的问题的一部分。 Not opposed to using the "this" pointer if there is a way to make it work in pure JS.如果有办法让它在纯 JS 中工作,不反对使用“this”指针。

Thanks in advance for your help!在此先感谢您的帮助!

I think this can be better done using event delegation .我认为使用事件委托可以更好地做到这一点。 It would look something like:它看起来像:

document.addEventListener(`keyup`, handle);

function handle(evt) {
  if (evt.target.dataset?.pattern === `comma`) {
    return inputComma(evt.target);
  }
}

function inputComma(elem) {...} 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM