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

时间:2012-03-15 17:25:06

标签: javascript jquery events dom

我有以下代码:

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

如何知道所谓的事件是“点击”还是“更改”?

3 个答案:

答案 0 :(得分:52)

event.type会为您提供所需的信息。

DEMO

另见: List of event types

$("#tipo-imovel").on("click change", function(event){
    console.log(event.type + " is fired");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<input type="text" id="tipo-imovel" />

答案 1 :(得分:10)

@Vega解决方案对于简单事件是正确的。但是,如果您对事件命名空间(即player.play),那么您也必须获取命名空间。例如,假设我触发事件:

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

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

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

答案 2 :(得分: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);
    });

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