addEventListener('keydown',handlekeydown,false) vs. .onkeydown working differently for replacing typed keystroke

泪湿孤枕 提交于 2020-05-29 06:21:41

问题


I am using a 'keydown' event to replace specific characters typed in an input textbox.

When I use:

document.getElementById('inputText').onkeydown = handleInputTextKeydown;

or the JQuery equivalent:

$('#inputText').on('keydown',handleInputTextKeydown);

I get the expected result - e.g. the keypress Shift+i displays as 'í'.

However if I use addEventListner as the keydown hook:

var tb = document.getElementById('inputText');
tb.addEventListener('keydown', handleInputTextKeydown, false); 

the input textbox displays both my substitute character (í) and 'I' (uppercase i) 'íI'.

Why does the addEventListener method differ from the two 'onkeydown' hooks?

My test browser is IE 11.

BTW: I am using a variant of the keydown text replace method that was in another stackoverflow post:

newKey = keyMap[keyPressed];                // Look for this key in our list of accented key shortcuts
    if (newKey === undefined) {
            return true;                        // Not in our list, let it bubble up as is
        } else {

        var oldValue, start, end;
        oldValue = this.value;                  // Insert the updated key into the correct position within the edit textbox.
        if (typeof this.selectionStart == "number" && typeof this.selectionEnd == "number") {
            start = this.selectionStart;
            end = this.selectionEnd;
            this.value = oldValue.slice(0, start) + newKey + oldValue.slice(end);
        }
                                                // Move the caret
        this.selectionStart = this.selectionEnd = start + 1;
        return false;

回答1:


Because you have to prevent the default behavior with the .addEventListener() version.

Returning false at the end of the handler to prevent the default behavior is a jQuery-specific feature and a feature of the .onkeydown property, but not something that works with .addEventListener('keydown').

You will need to call e.preventDefault() (for modern browsers) or set e.returnValue = false (for non-standard browsers).


This is more than you need to solve your problem, but when working in plain javascript, I use a cross browser event handling stub that allows me to return false like this:

// refined add event cross browser
function addEvent(elem, event, fn) {
    // allow the passing of an element id string instead of the DOM elem
    if (typeof elem === "string") {
        elem = document.getElementById(elem);
    }

    function listenHandler(e) {
        var ret = fn.apply(this, arguments);
        if (ret === false) {
            e.stopPropagation();
            e.preventDefault();
        }
        return(ret);
    }

    function attachHandler() {
        // normalize the target of the event
        window.event.target = window.event.srcElement;
        // make sure the event is passed to the fn also so that works the same too
        // set the this pointer same as addEventListener when fn is called
        var ret = fn.call(elem, window.event);   
        // support an optional return false to be cancel propagation and prevent default handling
        // like jQuery does
        if (ret === false) {
            window.event.returnValue = false;
            window.event.cancelBubble = true;
        }
        return(ret);
    }

    if (elem.addEventListener) {
        elem.addEventListener(event, listenHandler, false);
    } else {
        elem.attachEvent("on" + event, attachHandler);
    }
}


来源:https://stackoverflow.com/questions/19609537/addeventlistenerkeydown-handlekeydown-false-vs-onkeydown-working-different

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!