How to trigger events (onclick) with specific orde

2019-09-10 09:19发布

问题:

Possible Duplicate:
Trigger an event with Prototype

example, 3 onclick events in javascript/prototype. How to force prototype to run alert functions for dump "first!", "second!" and then "third!" value. Thanks and here is code that you can c/p:

<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/prototype/1.6.0.2/prototype.js"></script>
</head>
<body>
<script type="text/javascript">
//<![CDATA[
document.observe("dom:loaded", function() {
  $("go").observe("click", function() { alert('First!'); });
  $("go").observe("click", function() { alert('Third!'); });
  $("go").observe("click", function() { alert('Second!'); });
  });
//]]>
</script>
<form>
<input id="go" type="button" value="Click me!"  />
</form>
</body>
</html>

回答1:

Event handlers are functions in JavaScript, and functions are prime citizens in JavaScript. Usually a middle object contains the list of all handlers as an array. For example, in jQuery, data('events') holds the event handlers. Unless prototype has an straightforward, you should manually fetch all handlers, order them up and assign them back.

Or

As @gaby has said, you can bind them using correct order in you markup at first place.



回答2:

How about this:

var handlers = [func1, func2, func3];
$("go").observe("click", function() { 
    var i = 0, len = handlers.length;
    for(i; i<len;i++)
       handlers[i]();
});

There are improvements of course, but it's a general idea