I am trying to dynamically replace attributes via jQuery – inside my for loop I am making use of an .attr()-function and it works fine but JSLint is complaining:
Don't make functions within a loop.
I know that I can disable these specific test in the JSLint config but I want to understand how I could solve this by placing a corresponding function outside the loop and call that one accordingly when using .attr()
Old logic
for (var i = currentRowIndex + 1; i <= oldIndex; i++) {
[...]
selectorName.attr( 'name', function( index, name ) {
return name.replace( /\d+/g, newIndex );
} );
}
Desired logic
var replaceAttr = function( index, attr ) {
return attr.replace( /\d+/g, index );
};
for (var i = currentRowIndex + 1; i <= oldIndex; i++) {
[...]
selectorName.attr( 'name', replaceAttr( function( newIndex, name ) );
}
The problem
While the first one works nicely and targets / passes the name-attribute correctly the second code simply replaces an empty attribute. Still being quite new to JS I am not sure how to tackle this...
- Is there a problem with closure?
- How can I pass / set the target so that it is recognized and not just a string?
- Would creating a 'master'-function which includes the .attr()-step help?
Looking forward to learning about this :)
Thanks in advance!
$('#id'+ i).attr('attribute', 'value;);function( newIndex, 'name' )herenameas a string not variable parameterfor()loop. Show more code context and howselectorNameis definedselectorNamefunction