I am still new to Javascript. I need to attach a function to handle events on some of my HTML elements.
I am doing the following:
$('#iinp0').keyup(function(){keyReleased('iinp0');});
$('#iinp1').keyup(function(){keyReleased('iinp1');});
$('#iinp2').keyup(function(){keyReleased('iinp2');});
$('#iinp3').keyup(function(){keyReleased('iinp3');});
$('#iinp4').keyup(function(){keyReleased('iinp4');});
$('#iinp5').keyup(function(){keyReleased('iinp5');});
$('#iinp6').keyup(function(){keyReleased('iinp6');});
$('#iinp7').keyup(function(){keyReleased('iinp7');});
I was hoping I could apply the Don’t Repeat Yourself (DRY) principle with the following:
for (i=0;i<=7;i++) {
var tmp = 'iinp' + i;
$('#'+tmp).keyup(function(){keyReleased(tmp);});
}
but keyReleased() is not called with the proper values.
Is there a solution to this issue? I mean is there a simple way to attach my functions having a constant parameter?
Why not simply this:
You could even replace that long selector with an attribute selector:
which will select any element who’s id starts with
iinp.Note: This selector is a tad slower than the pure ID selectors – but is much easier to read and maintain (if you could qualify it with a tag selector, it’ll be a bit faster).