Tampermonkey:触发事件不适用于元素 [英] Tampermonkey: Trigger event does not work for element

查看:198
本文介绍了Tampermonkey:触发事件不适用于元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在提供程序有角度的应用程序之上使用Tampermonkey添加一些功能,但是我被这个简单的事情所困扰.我无法使用CodePen复制问题,因此我们将不得不寻求理论和建议.我会尽量保持具体.

I'm trying to add some functionality using Tampermonkey on top of a providers angular application but I'm stuck at this simple thing. I can't replicate the issue using CodePen so we're going to have to go for theories and suggestions. I'll try to be as specific as I can.

在页面加载时添加此间隔,以检查ID为serialNumberInput的输入是否可用.然后,我向该表单添加一个下拉列表,并向其附加一个onChange事件,以使用所选选项的值更新串行输入字段.但是,触发部分永远不会发生.当我手动输入它们但不与脚本一起输入时,它确实起作用.

Adding this interval when the page loads to check when an input with the id serialNumberInput is available. Then I'm adding a dropdown to the form, and attach an onChange event to it to update the serial input field with the value of the selected option. However, the trigger parts just never happens. It does work when I enter them manually, but not with the script.

var populateSerialNumbersTimer = setInterval(function(){

    var serial = $("input#serialNumberInput");

    if($(serial).length >= 1){

        $(serial).css("display", "inline").css("width", "50%");
        $(serial).after(deviceToSerialSelectionHTML);

        $("select#deviceToSerial").on("change", function(){
            $(serial).val($("select#deviceToSerial").val());
            $(serial).trigger("change");
            $(serial).trigger("blur");

        });

        clearInterval(populateSerialNumbersTimer);
    }
}, 200);

我已经考虑过这个问题,并考虑了序列号如何在文本字段中结束,该字段必须是可访问的.也许是我要触发的事件尚未在函数声明时声明?

I've thought about it and considering how the serial number ends up in the text field the field must be accessible. Maybe it's that the events that I'm trying to trigger has not been declared at the time of the function declaration?

建议表示赞赏.

推荐答案

看起来jQuery尝试以某种方式缓存事件.如果有人对它感兴趣,这就是我用本机javascript解决的方法:

It looks like jQuery tries to cache the event somehow. This is how I solved it with native javascript in case someone else is interested:

function triggerEvent(e, s){
    "use strict";
    var event = document.createEvent('HTMLEvents');
    event.initEvent(e, true, true);
    document.querySelector(s).dispatchEvent(event);
}

$("select#deviceToSerial").on("change", function(){

    serialNumberInput.val($("select#deviceToSerial").val());

    triggerEvent("change", "input#serialNumberInput");
    triggerEvent("blur", "input#serialNumberInput");

}

这篇关于Tampermonkey:触发事件不适用于元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆