简体   繁体   English

将 jQuery .change() 转换为纯 JavaScript/DOM

[英]Converting jQuery .change() to plain JavaScript/DOM

I'm developing an autofill extension.我正在开发一个自动填充扩展。 I want to fill an input field with a value, example value = "12345", and then trigger the equivalent of a jQuery $(element).change(), but in pure JavaScript/DOM.我想用一个值填充输入字段,例如 value = "12345",然后触发等效的 jQuery $(element).change(),但在纯 JavaScript/DOM 中。

I've tried dispatching the change method,我试过调度 change 方法,

document.querySelector("input[name=inputIWantToChange]").dispatchEvent(new Event("change"));

but the behavior is different than that of但行为与

$("[name=inputIWantToChange]").change()

Looking at jQuery's source code , it would appear that jQuery works by invoking the handler that you have bound to the event (with a fake event that it creates) when you call change() - which means that you're going to have to find a way to be able to invoke a function, and also have the event invoke the same function. 查看 jQuery 的源代码,当您调用change()时,jQuery 似乎通过调用您绑定到事件的处理程序(使用它创建的假事件change() - 这意味着您将必须找到一种能够调用函数的方法,也可以让事件调用相同的函数。 Consider the following:考虑以下:

var elem = document.querySelector("input[name=inputIWantToChange]");

elem.addEventListener("change", function (evt) {
    onElemChange() // Pass data from the event `evt` here, as needed
});

function onElemChange() {
    // Your handler method here
}

When you'd want to invoke a "change event" as you do with jQuery, you can then just call onElemChange with the information you'd have gotten from the event, assuming you'd want to use any of the information from the event.当您想像使用 jQuery 一样调用“更改事件”时,您可以使用从事件中获得的信息调用onElemChange ,假设您想使用事件中的任何信息.

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

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