Programmatically triggering events in Javascript for IE using jQuery

后端 未结 6 1050
陌清茗
陌清茗 2021-01-04 19:22

When an Event is triggered by a user in IE, it is set to the window.event object. The only way to see what triggered the event is by accessing the window.

6条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-04 20:28

    This is an endemic problem with jQuery datepickers and ASP validation controls. As you are saying, the wrong element cross-triggers an ASP NET javascript validation routine, and then the M$ code throws an error because the triggering element in the routine is undefined.

    I solved this one differently from anyone else I have seen - by deciding that M$ should have written their code more robustly, and hence redeclaring some of the M$ validator code to cope with the undefined element. Everything else I have seen is essentially a workaround on the jQuery side, and cuts possible functionality out (eg. using the click event instead of change).

    The bit that fails is

       for (i = 0; i < vals.length; i++) {
            ValidatorValidate(vals[i], null, event);
        }
    

    which throws an error when it tries to get a length for the undefined 'vals'.

    I just added

    if (vals) {
        for (i = 0; i < vals.length; i++) {
            ValidatorValidate(vals[i], null, event);
        }
    }
    

    and she's good to go. Final code, which redeclares the entire offending function, is below. I put it as a script include at the bottom of my master page or page.

    Yes, this does break upwards compatibility if M$ decide to change their validator code in the future. But one would hope they'll fix it and then we can get rid of this patch altogether.

    //  Fix issue with datepicker and ASPNET validators: redeclare MS validator code with fix
     function ValidatorOnChange(event) {
        if (!event) {
            event = window.event;
        }
        Page_InvalidControlToBeFocused = null;
        var targetedControl;
        if ((typeof (event.srcElement) != "undefined") && (event.srcElement != null)) {
            targetedControl = event.srcElement;
        }
        else {
            targetedControl = event.target;
        }
        var vals;
        if (typeof (targetedControl.Validators) != "undefined") {
            vals = targetedControl.Validators;
        }
        else {
            if (targetedControl.tagName.toLowerCase() == "label") {
                targetedControl = document.getElementById(targetedControl.htmlFor);
                vals = targetedControl.Validators;
            }
        }
        var i;
        if (vals) {
            for (i = 0; i < vals.length; i++) {
                ValidatorValidate(vals[i], null, event);
            }
        }
        ValidatorUpdateIsValid();
    }
    

提交回复
热议问题