Search code examples
javascriptjqueryjslint

jQuery .attr() function within loop


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!


Solution

  • You've made a slight error with externalising your function. The call to attr can take a function, but that means your function needs to return a function - this is often referred to as a closure.

    var replaceAttr = function(newIndex){
     return  function( index, attr ) {
       return attr.replace( /\d+/g, newIndex );
     }
    }
    
    for (var i = currentRowIndex + 1; i <= oldIndex; i++) {
    
      [...]
    
      selectorName.attr( 'name', replaceAttr(newIndex) );
    }