2013-05-13 115 views
1

我的问题是: (仅作为例子,不能使整体感):JavaScript函数参数声明

// make a function and pass part of the statement as argument 
function ExampleFunction(argument) { 
    document.getElementById('TestID')[0].style.argument = '#f00'; 
} 

// then later onload 
ExampleFunction(background); 

我发现它不以这种方式工作,但我不能找到怎么会是对的。 如果有人能改正这个例子,让我在路上,我会非常高兴和感激。

+0

可能重复:http://stackoverflow.com/questions/16413167/how-to-access-a-dynamic-property- objectname-variable – 2013-05-13 00:10:16

回答

2

首先document.getElementById返回单个元件(或空,如果没有元件被发现),所以不[0]。其次,如果你想引用的一个属性动态地使用[]符号

// make a function and pass part of the statement as argument 
function ExampleFunction(argument) { 
    document.getElementById('TestID').style[argument] = '#f00'; 
} 

// then later onload 
ExampleFunction('background'); 

http://jsfiddle.net/HM3mu/

+0

BIG BIG谢谢你的快速帮助:) – Simon 2013-05-13 00:15:24

+0

ps我忘记了[0]从一个不同的函数,我用它来复制它没有id的地方。但无论如何谢谢你纠正这一点:) – Simon 2013-05-13 00:16:25

-1

getElementById返回单个元素而不是集合。

正确的代码是:

document.getElementById('TestID').style.background = '#f00';