开发者

Inserting a Variable String into the javascript prototype expression

Pardon me for giving you a confusing title on this problem. I'm really confused and i don't know how to put it in other words.

So here is what I what to accomplish.

I am making a Custom Javascript Object to store data.

I have automated this process and inserted each instance of the object into an array.

I am making a loop statement to invoke the unique property value of each instance of the object.

When I want to use an expression, the property name of the object would be variable since i don't know which one it is.

Ba开发者_JAVA技巧sically I need to incorporate a string value into the prototype expression.

e.g

document.getElementById('text').style."fontsize"=value;

since I cannot do this directly, i thought possibly I could use the eval function:

eval('document.getElementById("text").style.' + buttons[i].cssvalue + '="39px";');

but this still doesn't work.

Can this be fixed or ss there an alternative way to accomplish this?

If there are some unclear stuff, please point out and I will try to elaborate.

Thanks in advance.


In javascript you can access properties of an object using this notation:

document.getElementById('text').style["fontSize"] = value;

So your code might be:

document.getElementById('text').style[buttons[i].cssvalue] = "39px";


I don't know if this helps or not but I made a utility function which I published to npm which allows you to put in a class name / element along with the CSS properties you're looking at getting. This will then return a Javascript object with the CSS properties and their values within it.

You can find it here on Github and NPM:

GitHub: https://github.com/tjcafferkey/stylerjs

NPM: https://www.npmjs.com/package/stylerjs


First thought, look at a Javascript library or framework like JQuery or Dojo they probably have already solved the problem you are looking at. We use JQuery at work but I prefer Dojo's design but it is more targeted at large web applications.

Other than that Jakub's solution should work.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜