동적으로 첨부된 이벤트 리스너의 존재 여부를 확인하는 방법은 무엇인가요?

내 문제는 다음과 같습니다. 동적으로 첨부 된 이벤트 리스너의 존재를 어떻게 든 확인할 수 있습니까? 아니면 DOM에서 <온 클릭> (?) 속성의 상태를 어떻게 확인할 수 있습니까? 나는 스택 오버플로와 같은 해결책을 찾기 위해 인터넷을 검색했지만 운이 없었습니다. 여기 내 HTML이 있습니다:

<a id="link1" onclick="linkclick(event)"> link 1 </a>
<a id="link2"> link 2 </a> <!-- without inline onclick handler -->

그런 다음 자바스크립트에서 동적으로 생성된 이벤트 리스너를 두 번째 링크에 첨부합니다:

document.getElementById('link2').addEventListener('click', linkclick, false);

코드는 잘 실행되지만 첨부된 리스너를 감지하려는 모든 시도가 실패합니다:

// test for #link2 - dynamically created eventlistener
alert(elem.onclick); // null
alert(elem.hasAttribute('onclick')); // false
alert(elem.click); // function click(){[native code]} // btw, what's this?

[jsFiddle은 여기 있습니다](https://jsfiddle.net/qv0k7Lor/). '2에 추가'를 클릭한 다음 '링크 2'를 클릭하면 이벤트가 정상적으로 실행됩니다, 하지만 <[링크 2] 테스트>는 항상 거짓을 보고합니다. 도와주실 수 있나요?

질문에 대한 의견 (5)
해결책

동적으로 연결된 이벤트 리스너의 존재 여부를 확인할 수 있는 방법이 없습니다.

이벤트 리스너가 첨부되어 있는지 확인할 수 있는 유일한 방법은 다음과 같이 이벤트 리스너를 첨부하는 것입니다:

elem.onclick = function () { console.log (1) }

그런 다음 '!!elem.onclick'(또는 이와 유사한 것)을 반환하여 이벤트 리스너가 온클릭에 첨부되었는지 테스트할 수 있습니다.

해설 (1)

I did 셈이에요.

const element = document.getElementById('div');

if (element.getAttribute('listener') !== 'true') {
     element.addEventListener('click', function (e) {
         const elementClicked = e.target;
         elementClicked.setAttribute('listener', 'true');
         console.log('event has been attached');
    });
}

요소의 생성 후 검사 때 bsc247-3 리스너에 경우 특수 속성이 존재합니다.

해설 (2)

제가 할 일은 함수 외부에 FALSE로 시작하여 이벤트를 첨부할 때 TRUE로 설정되는 부울을 만드는 것입니다. 이것은 이벤트를 다시 첨부하기 전에 일종의 플래그 역할을 할 것입니다. 다음은 이 아이디어의 예시입니다.

// initial load
var attached = false;

// this will only execute code once
doSomething = function() {
  if (!attached) {
    attached = true;
    //code
  }
} 

//attach your function with change event
window.onload = function() {
    var txtbox = document.getElementById("textboxID");
    if(window.addEventListener){
        txtbox.addEventListener("change", doSomething, false);
    } else if(window.attachEvent){
        txtbox.attachEvent("onchange", doSomething);
    }
}
해설 (1)
  • tl; dr *: 기본적으로 지원되는 믿지아니하며 아니요인 이렇게 할 수 없는 것입니다.

_

이를 위해서는 사용자 정의할 수 있는 유일한 방법은 그러니까말이야 약간만이라도 스토리지 객체에는 기록을 유지할 수 있는 리스너에 덧붙였다. 뭔가 따라 다음 선:

/* Create a storage object. */
var CustomEventStorage = [];
  • 함수 객체 및 합니다 수 있는 첫 단계 1:* 스트로지 트래버스하도록 반품하십시오 요소를 기록을 볼 때 요소 (또는 거짓값).
/* The function that finds a record in the storage by a given element. */
function findRecordByElement (element) {
    /* Iterate over every entry in the storage object. */
    for (var index = 0, length = CustomEventStorage.length; index < length; index++) {
        /* Cache the record. */
        var record = CustomEventStorage[index];

        /* Check whether the given element exists. */
        if (element == record.element) {
            /* Return the record. */
            return record;
        }
    }

    /* Return false by default. */
    return false;
}
  • 다음 단계 2:* 합니다 수 있는 기능 뿐만 아니라 스토리지 객체에는 리스너에 장착합니다 이벤트 리스너를 추가합니다.
/* The function that adds an event listener, while storing it in the storage object. */
function insertListener (element, event, listener, options) {
    /* Use the element given to retrieve the record. */
    var record = findRecordByElement(element);

    /* Check whether any record was found. */
    if (record) {
        /* Normalise the event of the listeners object, in case it doesn't exist. */
        record.listeners[event] = record.listeners[event] || [];
    }
    else {
        /* Create an object to insert into the storage object. */
        record = {
            element: element,
            listeners: {}
        };

        /* Create an array for event in the record. */
        record.listeners[event] = [];

        /* Insert the record in the storage. */
        CustomEventStorage.push(record);
    }

    /* Insert the listener to the event array. */
    record.listeners[event].push(listener);

    /* Add the event listener to the element. */
    element.addEventListener(event, listener, options);
}
  • 조건을 내건 것으로 실제 3:* 단계 질문을 합니다 다음 함수는 요소에 대한 이벤트 리스너를 추가되었음 확인하기 위해 지정된 경우이다.
/* The function that checks whether an event listener is set for a given event. */
function listenerExists (element, event, listener) {
    /* Use the element given to retrieve the record. */
    var record = findRecordByElement(element);

    /* Check whether a record was found & if an event array exists for the given event. */
    if (record && event in record.listeners) {
        /* Return whether the given listener exists. */
        return !!~record.listeners[event].indexOf(listener);
    }

    /* Return false by default. */
    return false;
}
  • 4:* 마지막으로 한 단계 합니다 에서 스토리지 객체에는 리스너에 기능을 삭제할 수 있습니다.
/* The function that removes a listener from a given element & its storage record. */
function removeListener (element, event, listener, options) {
    /* Use the element given to retrieve the record. */
    var record = findRecordByElement(element);

    /* Check whether any record was found and, if found, whether the event exists. */
    if (record && event in record.listeners) {
        /* Cache the index of the listener inside the event array. */
        var index = record.listeners[event].indexOf(listener);

        /* Check whether listener is not -1. */
        if (~index) {
            /* Delete the listener from the event array. */
            record.listeners[event].splice(index, 1);
        }

        /* Check whether the event array is empty or not. */
        if (!record.listeners[event].length) {
            /* Delete the event array. */
            delete record.listeners[event];
        }
    }

    /* Add the event listener to the element. */
    element.removeEventListener(event, listener, options);
}

_

  • Snippet:*

<! - begin 스니핏: js 숨기십시오: 진정한 콘솔: 진정한 바벨. &gt 거짓값 -;

window.onload = function () {
  var
    /* Cache the test element. */
    element = document.getElementById("test"),

    /* Create an event listener. */
    listener = function (e) {
      console.log(e.type + "triggered!");
    };

  /* Insert the listener to the element. */
  insertListener(element, "mouseover", listener);

  /* Log whether the listener exists. */
  console.log(listenerExists(element, "mouseover", listener));

  /* Remove the listener from the element. */
  removeListener(element, "mouseover", listener);

  /* Log whether the listener exists. */
  console.log(listenerExists(element, "mouseover", listener));
};

<script src = "https://cdn.rawgit.com/angelpolitis/custom-event-storage/master/main.js"></script>


<div id = "test" style = "background:#000; height:50px; width: 50px"></div>

끝 - &lt 스니핏 >;!

_

5 년 이상 지났으나 _although OP 게시하기를 사람들은 이 질문에 대한 답을 얻을 수 있습니다 (i believe 빛위에 자신하고 있어 향후 이 제안 또는 향상을 안심 할 수 있도록 한다. & # _을 128522.

해설 (0)

항상 사용하여 수동으로 확인할 수 있습니다 타임코드가 에번트리스트너 크롬 검사자를 경우 (예: 탭, 기존의 &quot Styles&quot 요소 있습니다. 그 후 닫으십시오 하위 탭이 하나 더. 이벤트 Listeners&quot ";). 모든 요소를 가지고 있는 부여하느뇨 목록니다 에번트리스트너스 링크됨 있습니다.

해설 (0)

가능한 복제본임을: https://stackoverflow.com/questions/28056716/check-if-an-element-has-event-listener-on-it-no-jquery/41137585. 부탁일세 내 대답을 할 수 있다.

다음은 위한 전략은 기본적으로 크롬 (Chrome) 브라우저:

getEventListeners(document.querySelector('your-element-selector'));
해설 (0)

다음은 동적으로 첨부된 이벤트 리스너의 존재를 확인하는 데 사용한 스크립트입니다. jQuery를 사용하여 이벤트 핸들러를 요소에 첨부한 다음 해당 이벤트(이 경우에는 '클릭' 이벤트)를 트리거했습니다. 이렇게 하면 이벤트 핸들러가 첨부된 경우에만 존재하는 이벤트 속성을 검색하고 캡처할 수 있습니다.

var eventHandlerType;

$('#contentDiv').on('click', clickEventHandler).triggerHandler('click');

function clickEventHandler(e) {
    eventHandlerType = e.type;
}

if (eventHandlerType === 'click') {
    console.log('EventHandler "click" has been applied');
}
해설 (1)

이렇게 하면, t # 39 타임코드가 doesn& 홀수입니다 보인다. 결국 추가 시간 it is it?

하고 싶은 경우 다음과 같은 (검증되지 않은) 할 수 있습니다.

var _addEventListener = EventTarget.prototype.addEventListener;
var _removeEventListener = EventTarget.prototype.removeEventListener;
EventTarget.prototype.events = {};
EventTarget.prototype.addEventListener = function(name, function, etc) {
   var events = EventTarget.prototype.events;
   if (events[name]==null) {
      events[name] = [];
   }

   if (events[name].indexOf(function)==-1) {
      events[name].push(function);
   }

   _addEventListener(name, function);
}
EventTarget.prototype.removeEventListener = function(name) {
   var events = EventTarget.prototype.events;

   if (events[name]!=null && events[name].indexOf(function)!=-1) {
      events[name].splice(events[name].indexOf(function), 1);
   }

   _removeEventListener(name, function);
}
EventTarget.prototype.hasEventListener = function(name) {
   var events = EventTarget.prototype.events;
   if (events[name]==null) {
      return false;
   }

   return events[name].length);
}
해설 (0)

그냥 이벤트 분리하십시오 추가하기 전에 있다.

document.getElementById('link2').removeEventListener('click', linkclick, false);
document.getElementById('link2').addEventListener('click', linkclick, false);
해설 (0)

그냥 있는 스크립트입니다 작성했습니까 이를 수 있습니다. 이 2 개의 글로벌 기능을 제공합니다. '하세벤트 (노드입니다 elm, 문자열 이벤트)' 와 '게테벤츠 (노드입니다 elm)' 이 활용할 수 있습니다. '방법' 이 될 것을 추가 / 레모비번트리스트너 수정되므로 프랑타르제 '프로토타입 (prototype)' 및 '이벤트를 통해 추가된 html 마크업 구문을 또는 javascript elm.on_event = 작동하지 않습니다.'

추가 정보 dell. 깃허브

  • [라이브 데모를] [2] *

  • Script:*

var hasEvent,getEvents;!function(){function b(a,b,c){c?a.dataset.events+=","+b:a.dataset.events=a.dataset.events.replace(new RegExp(b),"")}function c(a,c){var d=EventTarget.prototype[a+"EventListener"];return function(a,e,f,g,h){this.dataset.events||(this.dataset.events="");var i=hasEvent(this,a);return c&&i||!c&&!i?(h&&h(),!1):(d.call(this,a,e,f),b(this,a,c),g&&g(),!0)}}hasEvent=function(a,b){var c=a.dataset.events;return c?new RegExp(b).test(c):!1},getEvents=function(a){return a.dataset.events.replace(/(^,+)|(,+$)/g,"").split(",").filter(function(a){return""!==a})},EventTarget.prototype.addEventListener=c("add",!0),EventTarget.prototype.removeEventListener=c("remove",!1)}();
해설 (0)

39 는 크로스 브라우저 기능을 제공하는 것으로, t 좁히어 doesn& 이벤트에 대한 검색을 등록될 만큼 요소.

그러나 이는 통화 기능을 몇 가지 요소에 대한 그들의 개발 도구를 사용하는 브라우저 다시 볼 수 있습니다. 이 방법을 찾기 위해 충족하거나 디버깅 코드를 웹 페이지 기능을 할 때 유용하게 사용할 수 있습니다.

  • Firefox *

첫째, 보기입니다 요소에서 탭에 검사자를 개발자 도구를. 이 작업을 수행할 수 있습니다.

      • 마우스 오른쪽 버튼으로 클릭하면 해당 페이지의 웹 페이지의 검사하고, 검사 항목을 선택하면 보기할 &quot Element&quot. 을 선택합니다.
        • 콘솔이군요 내의 함수를 사용하여 같은 요소를 선택한 후 이 아이콘을 클릭하면 해당 도쿠망스케리셀레스 * 탭 검사자를 선택취소합니다 요소점 볼 수 있습니다.

등록된 모든 요소를 포함하는 경우 세부 종목으로 단어 이벤트 선택취소합니다 요소점 버튼를 보실 수 있습니다. 이를 클릭하면 등록된 요소와 이벤트를 볼 수 있게 해준다. 이벤트 옆에 화살표를 클릭하면 그에 대한 콜백 함수를 볼 수 있습니다.

  • 크롬 *

첫째, 보기입니다 요소 요소에 탭에 개발자 도구. 이 작업을 수행할 수 있습니다.

      • 마우스 오른쪽 버튼으로 클릭하면 해당 페이지의 웹 페이지에 보기할 검사 항목을 선택하여 &quot Inspect"; 메뉴에서
        • 콘솔이군요 내의 함수를 사용하여 같은 요소를 선택한 것을 선택하고 오른쪽 클릭하면 도쿠망스케리셀레스 요소 요소에 panel&quot windows용 "; * 탭에 있는 검사자를 봅니다.

창 섹선에서 근처에 있는 다른 단면을 보여 주는 나무를요 선행돼야 할 자격이 있는 웹 페이지 요소, 이벤트 탭을 &quot Listeners". 선택할 수 있는 이벤트를 볼 수 있도록 이 같은 등록 요소. 이 코드는 특정 이벤트에 대해 적절한 링크를 클릭하여 볼 수 있다.

구글 크롬, 이벤트 에서 요소의 게테벤트리스트너스 기능을 사용하여 볼 수도 있습니다. 그러나 게테벤트리스트너스 , t # 39 를 기반으로 내 시험 함수 doesn& 때 이벤트를 나열하십시오 여러 요소가 전달됩니다. 스케쳐내 찾을 수 있는 모든 페이지의 요소 및 보는 사람들을 위한 리스너에 리스너에 콜백 함수를 사용할 수 있습니다 다음 코드를 콘솔입니다 이 작업을 수행할 수 있습니다.


var elems = document.querySelectorAll('*');

for (var i=0; i 
해설 (0)

만약 내가 잘 이해할 수 있지만 그동안 점검됩니다 있는 것은 아니지만 특별히 발표자 리스너에 리스너에 확인합니다.

그래서 일부 ad hoc 코드를 처리하는 코딩 흐름을 이 공백을 메울 수 있을 것 "이라고 말했다. 'A' 상태 변수를 사용하여 만들 수 있는 현실적인 방법이 될 수 있다. 예를 들어, 다음과 같이 listener& 부착합니다 # 39 의 검사기에서.

var listenerPresent=false

그냥 리스너에 신앙이니라 설정한 값을 변경하십시오:

listenerPresent=true

& # 39 을 지정할 수 있습니다 다음 에번트리스트너 내의 특정 기능을 콜백하는 내부 및 이 방법은 같지만 분산합니다 액세스하려면 기능을 일부 스테이드 변수로 따라 예를 들면 다음과 같습니다.

accessFirstFunctionality=false
accessSecondFunctionality=true
accessThirdFunctionality=true
해설 (0)

이론적으로 addEventListener 및 레모비번트리스트너 등에 대한 추가 / 제거 할 수 있습니다 # 39, & # 39 는 플래깅 this&. 객체에는. 내가 haven& 추악한 # 39, t 테스트됨.

해설 (0)

난 그냥 내 행사는 확인하기 위해 노력하고 의해 발견된 이 아웃해야 첨부됩니다.

만약 당신이 그렇게:

item.onclick

it 반환되므로 &quot null";

만일 너희가:

item.hasOwnProperty('onclick')

해당 제품은 &quot TRUE";

그런 만큼 이는 &quot 사용할 때 addEventListener"; 이벤트 핸들러를 추가하는 것이 유일한 액세스하려면 통해 hasOwnProperty&quot ";). I wish I knew I haven& # 39, 연구, 아니면 어떻게 하지만 왜 뒤에을 있었느뇨 라고 설명을 찾을 수 없다.

해설 (1)