将document.getElementById设置为variable [英] Set document.getElementById to variable

查看:108
本文介绍了将document.getElementById设置为variable的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下作品:

    $ = document.form;
    x = $.name.value;

这不是:

    $ = document.getElementById;
    x = $("id").value;

有关为什么不起作用或如何制作的任何想法?

Any ideas on why this doesn't work or how to make it so?

推荐答案

这个的值取决于你如何调用该函数。

The value of this depends on how you call the function.

当您致电 document.getElementById 然后 getElementById 获取这===文件。将 getElementById 复制到另一个变量然后将其称为 $ 然后此== = window (因为 window 是默认变量)。

When you call document.getElementById then getElementById gets this === document. When you copy getElementById to a different variable and then call it as $ then this === window (because window is the default variable).

这会导致它在窗口对象中而不是在文档对象中查找id,并且由于窗口不是文档而且没有相同的方法,因此失败的可能性很大。

This then causes it to look for the id in the window object instead of in the document object, and that fails horribly because windows aren't documents and don't have the same methods.

您需要在通话中维护文档。你可以使用包装器函数,例如。

You need to maintain the document in the call. You can use a wrapper functions for this e.g.

function $ (id) { return document.getElementById(id); }

...但请不要使用 $ 。这是一个可怕的名字。它没有任何意义,它会让看到它的人感到困惑并想到啊!我知道jQuery!或者啊!我知道原型等等。

… but please don't use $. It is a horrible name. It has no meaning and it will confuse people who see it and think "Ah! I know jQuery!" or "Ah! I know Prototype" or etc etc.

这篇关于将document.getElementById设置为variable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆