내 문제는 다음과 같습니다. 동적으로 첨부 된 이벤트 리스너의 존재를 어떻게 든 확인할 수 있습니까? 아니면 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은 여기 있습니다](
). '2에 추가'를 클릭한 다음 '링크 2'를 클릭하면 이벤트가 정상적으로 실행됩니다, 하지만 <[링크 2] 테스트>는 항상 거짓을 보고합니다. 도와주실 수 있나요?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 리스너에 경우 특수 속성이 존재합니다.
제가 할 일은 함수 외부에 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);
}
}
_
이를 위해서는 사용자 정의할 수 있는 유일한 방법은 그러니까말이야 약간만이라도 스토리지 객체에는 기록을 유지할 수 있는 리스너에 덧붙였다. 뭔가 따라 다음 선:
/* Create a storage object. */
var CustomEventStorage = [];
/* 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;
}
/* 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);
}
/* 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;
}
/* 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);
}
_
<! - begin 스니핏: js 숨기십시오: 진정한 콘솔: 진정한 바벨. > 거짓값 -;
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));
};
<!-- Include the Custom Event Storage file -->
<script src = "https://cdn.rawgit.com/angelpolitis/custom-event-storage/master/main.js"></script>
<!-- A Test HTML element -->
<div id = "test" style = "background:#000; height:50px; width: 50px"></div>
끝 - < 스니핏 >;!
_
5 년 이상 지났으나 _although OP 게시하기를 사람들은 이 질문에 대한 답을 얻을 수 있습니다 (i believe 빛위에 자신하고 있어 향후 이 제안 또는 향상을 안심 할 수 있도록 한다. & # _을 128522.
다음은 동적으로 첨부된 이벤트 리스너의 존재를 확인하는 데 사용한 스크립트입니다. 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');
}
이렇게 하면, 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);
}
그냥 있는 스크립트입니다 작성했습니까 이를 수 있습니다. 이 2 개의 글로벌 기능을 제공합니다. '하세벤트 (노드입니다 elm, 문자열 이벤트)' 와 '게테벤츠 (노드입니다 elm)' 이 활용할 수 있습니다. '방법' 이 될 것을 추가 / 레모비번트리스트너 수정되므로 프랑타르제 '프로토타입 (prototype)' 및 '이벤트를 통해 추가된 html 마크업 구문을 또는 javascript elm.on_event = 작동하지 않습니다.'
[라이브 데모를] [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)}();
그러나 이는 통화 기능을 몇 가지 요소에 대한 그들의 개발 도구를 사용하는 브라우저 다시 볼 수 있습니다. 이 방법을 찾기 위해 충족하거나 디버깅 코드를 웹 페이지 기능을 할 때 유용하게 사용할 수 있습니다.
첫째, 보기입니다 요소에서 탭에 검사자를 개발자 도구를. 이 작업을 수행할 수 있습니다.
등록된 모든 요소를 포함하는 경우 세부 종목으로 단어 이벤트 선택취소합니다 요소점 버튼를 보실 수 있습니다. 이를 클릭하면 등록된 요소와 이벤트를 볼 수 있게 해준다. 이벤트 옆에 화살표를 클릭하면 그에 대한 콜백 함수를 볼 수 있습니다.
첫째, 보기입니다 요소 요소에 탭에 개발자 도구. 이 작업을 수행할 수 있습니다.
창 섹선에서 근처에 있는 다른 단면을 보여 주는 나무를요 선행돼야 할 자격이 있는 웹 페이지 요소, 이벤트 탭을 " Listeners". 선택할 수 있는 이벤트를 볼 수 있도록 이 같은 등록 요소. 이 코드는 특정 이벤트에 대해 적절한 링크를 클릭하여 볼 수 있다.
구글 크롬, 이벤트 에서 요소의 게테벤트리스트너스 기능을 사용하여 볼 수도 있습니다. 그러나 게테벤트리스트너스 , t # 39 를 기반으로 내 시험 함수 doesn& 때 이벤트를 나열하십시오 여러 요소가 전달됩니다. 스케쳐내 찾을 수 있는 모든 페이지의 요소 및 보는 사람들을 위한 리스너에 리스너에 콜백 함수를 사용할 수 있습니다 다음 코드를 콘솔입니다 이 작업을 수행할 수 있습니다.
var elems = document.querySelectorAll('*');
for (var i=0; i <= elems.length; i++) {
var listeners = getEventListeners(elems[i]);
if (Object.keys(listeners).length < 1) {
continue;
}
console.log(elems[i]);
for (var j in listeners) {
console.log('Event: '+j);
for (var k=0; k < listeners[j].length; k++) {
console.log(listeners[j][k].listener);
}
}
}
이 질문에 대해 이 작업을 수행할 수 있는 방법을 편집하십시오 경우 해당 브라우저나 다른 브라우저에서도.
만약 내가 잘 이해할 수 있지만 그동안 점검됩니다 있는 것은 아니지만 특별히 발표자 리스너에 리스너에 확인합니다.
그래서 일부 ad hoc 코드를 처리하는 코딩 흐름을 이 공백을 메울 수 있을 것 "이라고 말했다. 'A' 상태 변수를 사용하여 만들 수 있는 현실적인 방법이 될 수 있다. 예를 들어, 다음과 같이 listener& 부착합니다 # 39 의 검사기에서.
var listenerPresent=false
그냥 리스너에 신앙이니라 설정한 값을 변경하십시오:
listenerPresent=true
& # 39 을 지정할 수 있습니다 다음 에번트리스트너 내의 특정 기능을 콜백하는 내부 및 이 방법은 같지만 분산합니다 액세스하려면 기능을 일부 스테이드 변수로 따라 예를 들면 다음과 같습니다.
accessFirstFunctionality=false
accessSecondFunctionality=true
accessThirdFunctionality=true
난 그냥 내 행사는 확인하기 위해 노력하고 의해 발견된 이 아웃해야 첨부됩니다.
만약 당신이 그렇게:
item.onclick
it 반환되므로 " null";
만일 너희가:
item.hasOwnProperty('onclick')
해당 제품은 " TRUE";
그런 만큼 이는 " 사용할 때 addEventListener"; 이벤트 핸들러를 추가하는 것이 유일한 액세스하려면 통해 hasOwnProperty" ";). I wish I knew I haven& # 39, 연구, 아니면 어떻게 하지만 왜 뒤에을 있었느뇨 라고 설명을 찾을 수 없다.