问题
I’m trying to store a lot of text in an array (so I can easily pull it out using a value). The issue is within the strings I’d like to use template literals so the string changes depending on input (e.g. once they’ve added their name, it uses their name.
I can get this working no problem if I include the string in the function. For example:
textbox.textContent = `what does ${nameTemp} do?`;
That works no problem, it changes "nameTemp" to what the user inputted. But this below does not! It always returns "tim" as the name (the default value for "nameTemp")
textbox.textContent2 = Title[1];
You can see in the code below in the function saveName() that the first line (with the full string including the template literal does work. But the line below, using the string from the array (with the template literal in) does not update. It uses the default string ‘tim’. What am I doing wrong? How can i best store strings in an array that have chanagable elements? Thanks in advance for any suggestions.
var nameTemp = `tim`;
let Title = [];
Title[0] = "What are you called?";
Title[1] = `what does ${nameTemp} do?`;
const input = document.createElement('input');
input.type = "text";
input.id ="nameText";
input.className +='inputStyle';
function addNameInput()
{
container.appendChild(input);
}
function saveName()
{
if (nameText.value !== null)
{
nameTemp = nameText.value;
textbox.textContent = `what does ${nameTemp} do?`; //This works, it displays the inputed name
textbox.textContent2 = Title[1]; // This will always display 'tim'
nameText.parentNode.removeChild(nameText);
incrementState();
}
}
回答1:
Javascript template strings are evaluated when you first create them, and they don't magically update. Title[1]
is initialized with "tim"
, and even after you change the nameTemp
variable it'll remain the same. If you want to store template strings in an array then you can store a function that returns a template string, like:
Title[1] = () => `what does ${nameTemp} do?`;
then you can get the value via
textbox.textContent2 = Title[1]();
来源:https://stackoverflow.com/questions/61238955/how-to-store-strings-in-an-array-that-include-template-literals-javascript