Pregunta

I'm trying to put a string and a number together so a variable is in an image link, and so the variable formed by the string and number's value would display in the link, but instead the raw name just displays, not the variable's value.

      var link1 = 'restOfLink.gif';

      var myFunction = function(number){

      var imgLink = 'http://i60.tinypic.com/';

      var randomNumber = Math.floor((Math.random()*5)+1);

          $("div").append("<img src = '"+imgLink+'link'+randomNumber+"'/>");
       }

randomNumber won't always be 1 but let's just assume it is. The link shows up as http://i60.tinypic.com/link1.gif Any help on that? I'm trying to make an app that displays a new random image when a div is clicked. (the code above isn't all of the code, but it's enough to cover my problem)

¿Fue útil?

Solución

If you wanted to create a dynamic img element with a variable as the link or part of it you could do:

//These are just example variables, you can use your own the same way.
var imgPath = '/images/blog/';
var size = '200x450';

document.createElement('img').src =  imgPath + 'yourImage' + size + '.png';

JsFiddle Demo.


For your example i would suggest creating an array of links that you can access using a random number, for example:

var links = ['restOfLink.gif', 'anotherexample.png', 'yetanother.jpg'];

To select a particular image from inside the links array you need to pass it the index it occurs at, with 0 being the first.

So for example:

links[0] --> "restOfLink.gif"
links[1] --> "anotherexample.png"
links[2] --> "yetanother.jpg"

See this JsFiddle demo using this method.

Otros consejos

You should create the link string by concatenating the different parts in Javascript, and update the img src attribute afterwards. Something like:

var bar = 3;
var linkString = "http://www.foo.com/image_number_" + bar + ".jpg";

document.getElementById("yourImgId").src = linkString;

Best.

Dont know what you want. A JSFiddle would help as suggested but here is my try at a answer:

string = "lol";
number = 1;
source = string+number;

$(".element").attr('src', source+".jpg");

You need JQuery for this though.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top