【问题标题】:Get the name (type) of the event that was fired (triggered)获取触发(触发)的事件的名称(类型)
【发布时间】:2012-03-15 17:25:05
【问题描述】:

我有以下代码:

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

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

【问题讨论】:

    标签: javascript jquery events dom


    【解决方案1】:

    event.type 会得到你想要的。

    DEMO

    另请参阅: List of event types

    $('#button').on('click change', function(){
        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" />

    【讨论】:

    • 你的 HTML 中有错字:&lt;input type 不是 &lt;input tpys :)
    • 奇怪而不幸的是,“focus”的 event.type 是“focusin”,而不是“focus”。不确定其他事件是否有类似的怪癖。
    【解决方案2】:

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

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

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

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

    【讨论】:

      【解决方案3】:

      为了监听触发的事件,可以使用下面的 sn-p:

           $(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);
          });
      
      

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-07-31
        • 1970-01-01
        • 2017-02-11
        • 1970-01-01
        相关资源
        最近更新 更多