开发者

Is it possible to use a string variable to reference an element in Javascript?

开发者 https://www.devze.com 2022-12-26 15:40 出处:网络
Here\'s the quick version of the code as it stands right now: function foo(attributeName, someJSObj, key, newValue)

Here's the quick version of the code as it stands right now:

function foo(attributeName, someJSObj, key, newValue)
{
    someJSObj[key].attributeName = newValue;
}

Obviously this doesn't work, since it just creates a new element called attributeName. Is there an easy way to dereference the a开发者_JS百科ttributeName into the string that represents some existing attribute on someJSObj?


You need to use the bracket notation for attributeName as well:

function foo(attributeName, someJSObj, key, newValue)
{
    someJSObj[key][attributeName] = newValue;
}

Now the value of attributeName is used as identifier instead of the identifier attributeName itself.


If I understood you correctly, you could use ECMAScript

function foo(attributeName, someJSObj, key, newValue)
{
    someJSObj[key][attributeName] = newValue;
}

Hope this helps you.


Try someJSObj[key].setAttribute(attributeName, newValue)

0

精彩评论

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