How to disable JQuery keypress event for just one element?

喜欢而已 提交于 2019-12-03 07:19:01

问题


On my site I have registered a keypress event handler for the whole document.

$(document).keypress(myhandler);

And I handle the 'space' key to scroll a list.

Trouble is, there is an <input type='text' /> element, and I don't want 'space' keypress to scroll the list when it is entered in the input.

I couldn't find any information in the "event" object passed by JQuery to the handler, to identify where the source of the event is.


回答1:


Alternatively, you could attach another event handler to the input field, and in this handler stop the propagation of the event:

jQuery('#input-field-id').bind('keypress', function(e) {
    e.stopPropagation(); 
});

This way, you can leave the global event handler as it is. Might be cleaner.




回答2:


you're looking for event.target.id, which will be the id of the element that the event was raised on. So inside myhandler you would need something like the following

function myhandler(e) {
    if (e.target.id !== 'id of input') {
        /* rest of event handler */
    }
}



回答3:


See the QuirksMode docs about event order, and especially about how to turn off the events, which is browser-specific. Quote:

For a complete cross-browser experience do

function doSomething(e)
{
    if (!e) var e = window.event;
    e.cancelBubble = true;
    if (e.stopPropagation) e.stopPropagation();
}


来源:https://stackoverflow.com/questions/1708450/how-to-disable-jquery-keypress-event-for-just-one-element

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