获取被激发(触发)的事件的名称(类型)

问题描述 投票:0回答:3

我有以下代码:

$('#button').on('click change', function() {
    alert('Who fired me, click or change?');
});

我如何知道调用的事件是“点击”还是“更改”?

javascript jquery events dom
3个回答
81
投票

event.type
会给你你想要的。

演示

另请参阅: 事件类型列表

$('#button').on('click change', function(event){
    console.log(event.type + ' is fired');
});


17
投票

@Vega 解决方案对于简单事件是正确的。但是,如果您为事件命名空间(即

player.play
),那么您也必须获取命名空间。例如,假设我触发了事件:

$('#myElement').trigger('player.play');

然后要获取完整的事件名称,您需要执行以下操作:

$('#myElement').on('player.play', function(e) {
    console.log('Full event name: ' + e.type + '.' + e.namespace);
});

0
投票

要监听触发的事件,可以使用以下代码片段:

     $(document).on("abort activate afterprint beforeactivate beforecopy beforecut beforedeactivate beforepaste beforeprint beforeunload blur bounce change CheckboxStateChange click contextmenu copy cut dblclick deactivate deactivate DOMAttrModified DOMCharacterDataModified DOMFocusIn DOMFocusOut DOMMouseScroll DOMNodeInserted DOMNodeInsertedIntoDocument DOMNodeRemoved DOMNodeRemovedFromDocument DOMSubtreeModified drag dragdrop dragend dragenter dragexit draggesture dragleave dragover dragstart drop error error (window) finish focus focusin focusout hashchange help input keydown keypress keyup load message mousedown mouseenter mouseleave mousemove mouseout mouseover mouseup mousewheel offline online overflow overflowchanged paste RadioStateChange readystatechange readystatechange (XMLDocument) readystatechange (XMLHttpRequest) reset resize scroll search select selectionchange selectstart start stop submit textInput underflow unload ",function(e){
      console.log(e.type);
    });

有点长,但肯定会有帮助。:)

© www.soinside.com 2019 - 2024. All rights reserved.