简体   繁体   English

在 Javascript 中访问所有事件侦听器

[英]Access all event listeners in Javascript

I want to do something like this:我想做这样的事情:

function('string', function2(){})

where I leave the to user to write what he wants in the string parameter and than execute function2 .我让用户在string参数中写入他想要的内容,然后执行function2 The catch is here: string is an event listener.问题在这里: string是一个事件侦听器。 When the user writes click , I want to call onClick() , when the user writes mouse I want to call onMouseOver and so on.当用户写click 时,我想调用onClick() ,当用户写鼠标时我想调用onMouseOver等等。

I have in mind doing something with case , but how can I access all event listeners?我想用case做一些事情,但是如何访问所有事件侦听器?

You should use addEventListener .您应该使用addEventListener

element.addEventListener("string", function() {}, false);

However, in the case of IE <= 8, you will need to use attachEvent as it does not follow the standard:但是,在 IE <= 8 的情况下,您将需要使用attachEvent因为它不遵循标准:

element.attachEvent("string", function() {});

Finally, as kybernetikos mentions in his comment, you can then use a simple dictionary to map mouse to mouseover .最后,正如 kybernetikos 在他的评论中提到的,您可以使用一个简单的字典将mouse映射到mouseover

If you wish to fire events, you should use dispatchEvent .如果你想触发事件,你应该使用dispatchEvent

If you add the event listeners using the old model (ie elem.onclick = function(){ /* */ }; ), you can use如果您使用旧模型(即elem.onclick = function(){ /* */ }; )添加事件侦听器,则可以使用

elem['on' + event]();

Keep in mind that this only fires the event listeners, but doesn't create an event (eg it won't bubble).请记住,这只会触发事件侦听器,但不会创建事件(例如,它不会冒泡)。

If you won't to create a event, which fires event listeners added using addEventlistener , and bubbles, and does all things a real event does, you must如果您不想创建一个事件,它会触发使用addEventlistener添加的事件侦听器和气泡,并执行真实事件所做的所有事情,您必须

  1. Create your event using event constructors: Event or CustomEvent使用事件构造函数创建事件: EventCustomEvent
  2. Fire it with dispatchEventdispatchEvent触发它

See MDN page for more information and examples.有关更多信息和示例,请参阅MDN 页面

you can use .trigger to do this.你可以使用 .trigger 来做到这一点。 Check out this example in jsfiddle.在 jsfiddle 中查看此示例。 type "dblclick" in the input box.在输入框中输入“dblclick”。

http://jsfiddle.net/jspatel/Suj4H/1/ http://jsfiddle.net/jspatel/Suj4H/1/

<input id="writehere"> </input>
  $('#writehere').dblclick(function() {
     alert ('dblclick');
   });


$('#writehere').bind('keypress', function(e) {
    if(e.keyCode==13){
        $(this).trigger( $(this).val() );
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM