0

I'm creating some logic for dom scripting and end up finding the problem where I needed to execute multiple methods when pressing a key. It seems the last onkeyup defined is the one which executes, here's some code:

First method:

...var elements=$$('[id^='+table+']&[id$='+tableField+']');

elements.each(function filter(item) {
    
    //for each item 
    item.onkeyup = function() { ...

Second method:

...//for each referenced input    
for(var i=0, fields=htmlFieldElems.length;i<fields;i++){

   //set keyup event for involved fiels in the expression
   $(htmlFieldElems[i]).onkeyup = function() {...
        

It might happen that the input element might be the same in both methods and both need to execute when something changes... so what's the best way to deal with this?

4

2 回答 2

2

This is what I follow using jQuery. Here is an example

$('#element').bind('customE',function(){
   // do some stuff
});

$('#element').bind('customE',function(){
   // do some other interesting stuff else use one event handler :-)
});

$('#element').bind('customE',function(){
   // still another
});

$('#element').on('keyup',function(){
    $('#element').trigger('customE');   
});

Hope this helps.. even other answer posted would help.. But this will be easy to maintain :-)

于 2013-02-16T15:48:38.540 回答
1

in pure javascript, you can just call multiple methods from your onkeyup event handler, like this ...

item.onkeyup = function() {
    func1();
    func2();
    funcn();
}

if you are using a framework such as jQuery, you can just keep adding events, like this:

$('#item').keyup(func1);
$('#item').keyup(func2);
$('#item').keyup(funcn);

Prototype:

$('foo').observe('keyup', function(event) {
    func1();
    func2();
    funcn();
});
于 2013-02-16T15:44:36.737 回答