DOM 요소의 모든 이벤트를 어떻게 바인딩 할 수 있습니까?
이벤트 각 를 개별적으로 나열하지 않고 jQuery를를 사용하여 DOM의 요소 모든 이벤트 (예 click
: keypress
, mousedown
)를 바인딩하려면 어떻게 해야 우리합니까?
예 :
$('#some-el').bind('all events', function(e) {
console.log(e.type);
});
모든 이벤트를 테스트하는 방법이 있습니다.
function getAllEvents(element) {
var result = [];
for (var key in element) {
if (key.indexOf('on') === 0) {
result.push(key.slice(2));
}
}
return result.join(' ');
}
그런 다음 다음과 같이 모든 이벤트를 바인딩하십시오.
var el = $('#some-el');
el.bind(getAllEvents(el[0]), function(e) {
/* insert your code */
});
또한 jQuery.event.trigger를 재정의하는 각 이벤트가 아닌 API를 탐색하는 데만 유용 할 외부 생각합니다.
var oldJQueryEventTrigger = jQuery.event.trigger;
jQuery.event.trigger = function( event, data, elem, onlyHandlers ) {
console.log( event, data, elem, onlyHandlers );
oldJQueryEventTrigger( event, data, elem, onlyHandlers );
}
jQuery는 이벤트를 저장하는 방법을 변경하는 사용중인 버전에 따라 목록을 추출 하는 몇 가지 방법 이 있습니다. 나는 한 플러그인에서 "가장 최신 '버전의 캡슐화 하지만 기본적으로 당신이 원하는 :
var events = $._data($('yourelement')[0], "events");
이렇게하면 "기본"이벤트 (네임 스페이스 없음)로 그룹화 된 모든 바인딩 된 이벤트의 중첩 목록이 제공됩니다.
그러나 모든 기본 jQuery 이벤트를 원한다는 것을 깨달았습니다. $.event
는 아래에 일부있는을 검사 할 수 $.event.special
있지만 수락 된 답변 은 여전히 최선의 선택 일 수 있습니다. 또한 가능한 바인딩 함수로 jQuery가 제안 하는 것을 볼 수 있습니다 .
여러 이벤트를 동일한 함수에 비용 청구 공백으로 구분하면됩니다.
$("#test").bind("blur focus focusin focusout load resize scroll unload click " +
"dblclick mousedown mouseup mousemove mouseover mouseout mouseenter " +
"mouseleave change select submit keydown keypress keyup error", function(e){
$("#r").empty().text(e.type);
});
다음은 jQuery에 대한 작은 확장입니다.
$.fn.onAny = function(cb){
for(var k in this[0])
if(k.search('on') === 0)
this.on(k.slice(2), function(e){
// Probably there's a better way to call a callback function with right context, $.proxy() ?
cb.apply(this,[e]);
});
return this;
};
용법 :
$('#foo').onAny(function(e){
console.log(e.type);
});
또한 브라우저 콘솔을 사용할 수 있습니다 ( 이 답변에서 ).
monitorEvents($0, 'mouse'); // log all events of an inspected element
monitorEvents(document.body); // log all events on the body
monitorEvents(document.body, 'mouse'); // log mouse events on the body
monitorEvents(document.body.querySelectorAll('input')); // log all events on inputs
jQuery가 와일드 카드를 지원하지 않는다고 생각합니다 (어렵고 위험이 따릅니다).하지만 표준 이벤트 목록은 한정되어 있습니다 (슬프게도 DOM2 이벤트 사양 , DOM2 HTML 사양 및 DOM3 이벤트에 걸쳐 약간 퍼져 있습니다. spec ), 언제든지 간단히 나열 할 수 있습니다. jQuery를 사용하면 바인딩 할 여러 이벤트 이름 (공백으로 구분)을 지정할 수 있습니다. 예 :
$('#some-el').bind('click dblclick mouseover mouseout' /* etc.*/,function(e){
console.log(e.type);
});
나는 Mark Coleman의 대본을 가져 와서 내 필요에 맞게 약간 향상 시켰습니다.
당신과 공유하고 싶습니다 : http://jsfiddle.net/msSy3/65/
var lastEvent = null,
countEvent = 0;
$("#test").bind("blur focus focusin focusout load resize scroll unload click" + " dblclick mousedown mouseup mousemove mouseover mouseout mouseenter " + "mouseleave change select submit keydown keypress keyup error", function (e) {
if (lastEvent !== e.type) {
countEvent++;
$("#r").prepend("<span>" + countEvent + ": " + e.type + "<br></span>");
$("#r > span:nth-child(21)").remove();
lastEvent = e.type;
}
});
참고 URL : https://stackoverflow.com/questions/5848598/how-can-i-bind-all-events-on-a-dom-element
'ProgramingTip' 카테고리의 다른 글
여러 연결을 만들 때 C에서 소켓 시간 초과를 설정하는 방법은 무엇입니까? (0) | 2020.11.30 |
---|---|
Perl은 한 줄씩 읽습니다. (0) | 2020.11.30 |
Excel에서 1 시간 추가 (0) | 2020.11.30 |
EPPlus 사용시 Column Type 설정 방법 (0) | 2020.11.30 |
SSRS에서 새 보고서를 사용했을 때 "같은 키가있는 항목이 이미 추가되었습니다"라는 오류가 발생하는 이유는 무엇입니까? (0) | 2020.11.30 |