简体   繁体   中英

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.

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?

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.

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. I tried to get around that issue by referencing the iterating object but I think that may be part of my problem. Not opposed to using the "this" pointer if there is a way to make it work in pure JS.

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) {...} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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