简体   繁体   中英

JavaScript using innerHTML and dynamic value passing to innerHTML

var greentext='shopping';
var colors=new Array('green','blue','red','violet','brown');
for(i=0;i<colors.length;i++)
{
 //suppose consider colors[i] is green
}

When concatenating colors[i]+'text' and passing to some div using innerHTML , the string "greentext" is passed rather than the value of the concatenated string "shopping" . How to pass the value of dynamically created string as above?

Hope my question is clear.....please help me

I'd do it completely differently:

  var text = {
    green: 'shopping',
    blue: 'contemplating infinity',
    red: 'cooking beans',
    violet: 'writing poetry'
  };

  var colors = ['green', 'blue', 'red', 'violet' ];
  for (var i = 0; i < colors.length; ++i) {
    alert( text[ colors[i] ] );
  }

Structured data should preferably be represented with actual structures in whatever programming language you're using. JavaScript is flexible enough that you can "construct" variable names, but it's not idiomatic. Here, I've made a simple object with properties corresponding to your colors.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM