Is it possible from a function parameter to call the value of a variable with Template strings?

Asked

Viewed 73 times

-4

In my function below, it works perfectly in relation to the src from the image, it brings the image based on example1.png, example2.png... But when printing in innerHTML (I also tested with innerText), it doesn’t print the value of the variable, it writes in html "text1", "text2", and "text3", when in fact I need the value of them. Is there any way to make this work?

const text1 = "bla"
const text2 = "bla bla"
const text3 = "bla bla bla"

function blaBla(foo) {
  elemento.src = `images/"exemplo" + ${foo} + ".png"`
  elemento2.innerHTML = `"text" + ${foo}`
}

botao.onclick = () => {
  blaBla("1");
}

botao2.onclick = () => {
  blaBla("2");
}

botao3.onclick = () => {
  blaBla("3");
}

  • 2

    The identifier var is a identifier reserved by the interpreter do not use it as a variable. See here a discussion about the problem and the use of reserved words as an identifier. Make the correction in your example.

  • 2

    It would also be nice if you put HTML in the question to form a [MCVE]. Directly you can not do what you want to do but there are alternatives that do not use.

1 answer

-2


Place the texts inside an array or an object:

const text = {1:'bla',2:'blabla',3:'blablabla'};
elemento2.innerHTML = `${text[propName]}`
  • 1

    As Augutso has already commented: The identifier var is a identifier reserved by the interpreter do not use it as a variable. Your reply will make a mistake because of text[var].

  • 1

    @Cmtecardeal, vdd and I who had given up the answer and passed hit that var.

  • 3

    Out you don’t even need to put the expression (syntactically invalid, as noted above) text[var] within an interpolation that adds no other content. Just something like text[propName] would already solve.

  • Ah, it was just an example, I was not using var, but I will change here! And his answer served me!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.