0

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!

6
  • create the ids to be numeric, then define the selector in the loop as $('#id'+ i).attr('attribute', 'value;); Commented May 24, 2017 at 10:17
  • function( newIndex, 'name' ) here name as a string not variable parameter Commented May 24, 2017 at 10:17
  • @ThisGuyHasTwoThumbs What do you mean by that? My IDs are fine, the selctors work, I just didn't post the full code but can add that if needed... Commented May 24, 2017 at 10:28
  • 1
    Probably don't need the for() loop. Show more code context and how selectorName is defined Commented May 24, 2017 at 10:31
  • The problem is, you did not show code of selectorName function Commented May 24, 2017 at 11:09

1 Answer 1

1

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) );
}
Sign up to request clarification or add additional context in comments.

1 Comment

Great!! Thanks, will have to do some more work on closures then...!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.