开发者

Why doesn't this getElementById function work?

<div id="t">gf</div>
<div id="g">ds</div>

fu开发者_高级运维nction $() {
    return document.getElementById(arguments);
}

$('t', 'g').style.color = "red";

Is there something that I did wrong. It says cannot call style of null...


function $() {
    return document.getElementById.apply(document, arguments);
}

You need to use the apply method to call a function using an an array as the arguments. The apply function also needs the context, so you need to pass document as well.

Also, getElementById only accepts a single argument and returns a single element (AFAIK), so this is basically useless. Not to mention even if it did accept multiple arguments to return multiple elements, you still wouldn't be able to use the resulting array in that manner.


function $(a, f) {
    a.forEach(function(id) {
        f(document.getElementById(id));
    });
}
$(['t', 'g'], function(d) {
    d.style.color = "red";
});
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜