1

Trying to dynamically set variables depending how many vimeo iframes are on my page. Im using the Eval method in my code below:

var numberVimeoFrames = jQuery(".vimeo").length;

for(i=1;i<=numberVimeoFrames;i++){
    var refFrame = jQuery('.vimeo:nth-child(' + i + ')');
    eval("player" + i + "= new Vimeo.Player(" + refFrame + ")");
}

My eval line is however generating an error message:

Uncaught SyntaxError: Unexpected identifier

To me it looks like ive concatenated correctly so not sure where ive gone wrong?

6
  • 1
    refFrame is a jQuery object, not a string, it doesn't make sense to concatenate it. Commented Jan 12, 2017 at 17:26
  • 11
    Any time you think you need dynamic variables, you're probably wrong. You should be using an array or object. When the variables have numeric suffixes like this, it should be an array. Commented Jan 12, 2017 at 17:27
  • How could it be done with an array? Commented Jan 12, 2017 at 17:28
  • 3
    player[i] = new Vimeo.Player(refFrame); Commented Jan 12, 2017 at 17:29
  • 1
    Did you consider var players = jQuery(".vimeo") and then players[i]? Commented Jan 12, 2017 at 17:44

1 Answer 1

1

Even though in this case I do not think it is that bad, the general opinion is to not use eval at all. Use arrays instead :

var numberVimeoFrames = jQuery(".vimeo").length;

var players = [];
for(i=1;i<=numberVimeoFrames;i++){
    var refFrame = jQuery('.vimeo:nth-child(' + i + ')');
    players.push(new Vimeo.Player(refFrame));
}

You can now access your players by calling the array (for example players[1] instead of player1 and so on.)

Sign up to request clarification or add additional context in comments.

Comments

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.