JavaScript函数参数语句

时间:2013-05-13 00:08:27

标签: javascript function arguments

我的问题是: (仅作为示例,总体上没有意义):

// 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 );

我发现它不能这样工作,但我不知道它是怎么回事。 如果有人能够纠正这个例子,让我按照我的方式发送给我,我将非常高兴和感激。

2 个答案:

答案 0 :(得分:2)

首先document.getElementById返回单个元素(如果没有找到元素,则返回null),因此不是[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/

答案 1 :(得分:-1)

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

正确的代码是:

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