1

here my code which is not working properly. (it is working if on line 4 I write $("img").attr("src", image_src_1); )

I guess I have to "variablize" line 4.

<script>
  var image_src_1 = "image.jpg";
  var x = 1;
  var new_source_for_image = "image_src_" + x; // I WANT IT TO BE image_src_1
  $("img").attr("src", new_source_for_image);  // (line 4)
</script>

<body>
  <img src="">
</body>
1
  • Doesn't var new_source_for_image = "image_src_" + x need a file extension adding? Commented Mar 4, 2015 at 15:05

2 Answers 2

2

that is because new_source_for_image represents name of variable and not variable itself. You need to use .eval() for evaluating the value out of it:

 $("img").attr("src", eval(new_source_for_image));  

Working Demo

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

Comments

1

Take a look at eval http://www.w3schools.com/jsref/jsref_eval.asp. But, be careful to make sure you trust the data you run through eval. User data can be executed.

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.