[javascript] jQuery의 요소에 의해 발생한 모든 이벤트를 어떻게 기록합니까?

사용자 가 입력 필드 와 상호 작용할 때 입력 필드에서 발생하는 모든 이벤트를보고 싶습니다 . 여기에는 다음과 같은 항목이 포함됩니다.

  1. 그것을 클릭합니다.
  2. 그것을 클릭합니다.
  3. 그것에 탭.
  4. 그것에서 멀리 탭.
  5. Ctrl키보드의 + CCtrl+ V.
  6. 오른쪽 클릭-> 붙여 넣기.
  7. 오른쪽 클릭-> 잘라 내기.
  8. 오른쪽 클릭-> 복사.
  9. 다른 응용 프로그램에서 텍스트 끌어서 놓기.
  10. Javascript로 수정.
  11. Firebug와 같은 디버그 도구로 수정합니다.

을 사용하여 표시하고 싶습니다 console.log. Javascript / jQuery에서 가능합니까? 그렇다면 어떻게해야합니까?



답변

$(element).on("click mousedown mouseup focus blur keydown change",function(e){
     console.log(e);
});

이벤트가 발생했는지에 대한 정보를 많이 (전부는 아님) 얻을 수 있습니다. 이렇게 수동으로 코딩하는 것 외에는 다른 방법을 생각할 수 없습니다.


답변

아무도 이것을 사용하지 않는 이유를 모르겠습니다 … (아마도 웹킷 일뿐이기 때문에)

콘솔 열기 :

monitorEvents(document.body); // logs all events on the body

monitorEvents(document.body, 'mouse'); // logs mouse events on the body

monitorEvents(document.body.querySelectorAll('input')); // logs all events on inputs


답변

.data ( ‘events’) 컬렉션을 사용하는 좋은 일반적인 방법이 있습니다.

function getEventsList($obj) {
    var ev = new Array(),
        events = $obj.data('events'),
        i;
    for(i in events) { ev.push(i); }
    return ev.join(' ');
}

$obj.on(getEventsList($obj), function(e) {
    console.log(e);
});

이 특정 이벤트가 발생하는 순간 jQuery에 의해 요소에 이미 바인딩 된 모든 이벤트를 기록합니다. 이 코드는 저에게 여러 번 도움이되었습니다.

Btw : 개체에서 발생하는 모든 가능한 이벤트를 보려면 firebug를 사용하십시오. html 탭에서 DOM 요소를 마우스 오른쪽 버튼으로 클릭하고 “Log Events”를 선택하십시오. 그런 다음 모든 이벤트가 콘솔에 기록됩니다 (모든 마우스 움직임을 기록하기 때문에 때때로 약간 짜증이납니다 …).


답변

$('body').on("click mousedown mouseup focus blur keydown change mouseup click dblclick mousemove mouseover mouseout mousewheel keydown keyup keypress textInput touchstart touchmove touchend touchcancel resize scroll zoom focus blur select change submit reset",function(e){
     console.log(e);
}); 


답변

이에 대한 답은 이미 받아 들여졌지만 이벤트 이름을 미리 알 필요가없는 약간 더 안정적인 방법이있을 수 있다고 생각합니다. 이것은 내가 아는 한 기본 이벤트에서만 작동하며 플러그인으로 만든 사용자 정의 이벤트에는 적용되지 않습니다. 나는 jQuery의 사용을 생략하기로 결정했다.

let input = document.getElementById('inputId');

Object.getOwnPropertyNames(input)
  .filter(key => key.slice(0, 2) === 'on')
  .map(key => key.slice(2))
  .forEach(eventName => {
    input.addEventListener(eventName, event => {
      console.log(event.type);
      console.log(event);
    });
  });

나는 이것이 이것을 읽는 모든 사람에게 도움이되기를 바랍니다.

편집하다

그래서 여기 에서 비슷한 다른 질문을 보았 으므로 다른 제안은 다음을 수행하는 것입니다.

monitorEvents(document.getElementById('inputId'));


답변

오래된 실, 알아요. 이벤트를 모니터링 할 무언가가 필요했고이 매우 편리한 (우수한) 솔루션을 작성했습니다. 이 후크로 모든 이벤트를 모니터링 할 수 있습니다 (Windows 프로그래밍에서는 후크라고 함). 이 후크는 소프트웨어 / 프로그램의 작동에 영향을주지 않습니다.

에서 콘솔 로그인 이 같은 것을 볼 수 있습니다 :

콘솔 로그

당신이 보는 것에 대한 설명 :

콘솔 로그에서 선택한 모든 이벤트를 볼 수 있습니다 (아래 “사용 방법” 참조). )와 객체 유형, 클래스 이름, ID, <: 기능 이름>, <: 이름>이 표시됩니다. 개체의 서식은 CSS와 유사합니다.

버튼이나 바인딩 된 이벤트를 클릭하면 콘솔 로그에 표시됩니다.

내가 작성한 코드 :

function setJQueryEventHandlersDebugHooks(bMonTrigger, bMonOn, bMonOff)
{
   jQuery.fn.___getHookName___ = function()
       {
          // First, get object name
         var sName = new String( this[0].constructor ),
         i = sName.indexOf(' ');
         sName = sName.substr( i, sName.indexOf('(')-i );

         // Classname can be more than one, add class points to all
         if( typeof this[0].className === 'string' )
         {
           var sClasses = this[0].className.split(' ');
           sClasses[0]='.'+sClasses[0];
           sClasses = sClasses.join('.');
           sName+=sClasses;
         }
         // Get id if there is one
         sName+=(this[0].id)?('#'+this[0].id):'';
         return sName;
       };

   var bTrigger        = (typeof bMonTrigger !== "undefined")?bMonTrigger:true,
       bOn             = (typeof bMonOn !== "undefined")?bMonOn:true,
       bOff            = (typeof bMonOff !== "undefined")?bMonOff:true,
       fTriggerInherited = jQuery.fn.trigger,
       fOnInherited    = jQuery.fn.on,
       fOffInherited   = jQuery.fn.off;

   if( bTrigger )
   {
    jQuery.fn.trigger = function()
    {
     console.log( this.___getHookName___()+':trigger('+arguments[0]+')' );
     return fTriggerInherited.apply(this,arguments);
    };
   }

   if( bOn )
   {
    jQuery.fn.on = function()
    {
     if( !this[0].__hooked__ )
     {
       this[0].__hooked__ = true; // avoids infinite loop!
       console.log( this.___getHookName___()+':on('+arguments[0]+') - binded' );
       $(this).on( arguments[0], function(e)
       {
         console.log( $(this).___getHookName___()+':'+e.type );
       });
     }
     var uResult = fOnInherited.apply(this,arguments);
     this[0].__hooked__ = false; // reset for another event
     return uResult;
    };
   }

   if( bOff )
   {
    jQuery.fn.off = function()
    {
     if( !this[0].__unhooked__ )
     {
       this[0].__unhooked__ = true; // avoids infinite loop!
       console.log( this.___getHookName___()+':off('+arguments[0]+') - unbinded' );
       $(this).off( arguments[0] );
     }

     var uResult = fOffInherited.apply(this,arguments);
     this[0].__unhooked__ = false; // reset for another event
     return uResult;
    };
   }
}

사용 방법의 예 :

모든 이벤트 모니터링 :

setJQueryEventHandlersDebugHooks();

모든 트리거 만 모니터링 :

setJQueryEventHandlersDebugHooks(true,false,false);

모든 ON 이벤트 만 모니터링 :

setJQueryEventHandlersDebugHooks(false,true,false);

모든 OFF 바인딩 해제 만 모니터링 :

setJQueryEventHandlersDebugHooks(false,false,true);

비고 / 공지 :

  • 디버깅 용으로 만 사용하고, 제품 최종 버전에서 사용할 때는 끄십시오.
  • 모든 이벤트를 보려면 jQuery가로드 된 직후이 함수를 호출해야합니다.
  • 더 적은 이벤트 만보고 싶다면 필요한 시간에 함수를 호출 할 수 있습니다.
  • 자동 실행하려면 () (); 주변 기능

도움이 되었기를 바랍니다. 😉


답변

https://github.com/robertleeplummerjr/wiretap.js

new Wiretap({
  add: function() {
      //fire when an event is bound to element
  },
  before: function() {
      //fire just before an event executes, arguments are automatic
  },
  after: function() {
      //fire just after an event executes, arguments are automatic
  }
});