3

我通常通过执行以下操作为某些事件注册 javascript 函数:

myBtn.Attributes.Add("onClick", "Validate(getElementById('"+txtFirstName.ClientID + "'));");

我一直单独使用getElementById,或者换句话说,没有附加文件。但是最近当我尝试使用getElementById而不是document.getElementById. 为什么是这样?奇怪的是,我有一个网站,其中一个页面允许我使用 just getElementById,但另一个页面会引发 javascript 错误,因为如果我这样做它就找不到元素getElementById,而且只有我这样做它才会起作用document.getElementById

有谁知道这是为什么?我应该在document.getElementById任何地方使用,不管它是否在没有文档前缀的情况下工作?

编辑:这与一页使用 AJAX 而另一页不使用这一事实有什么关系吗?

4

6 回答 6

7

When you use getElementById() and it works that mean that the function where it's called is running on the context of the document, that's is this == document.

So, you should ALWAYS use document.getElementById to avoid that kind of errors.

Anyway, I would even stop using getElementById altogether and start using JQuery, i'm sure you'll never regret it.

Your code would look something like this if you used JQuery:

$("#myBtnID").click(function () { Validate($("#myTextboxID"))});
于 2009-05-12T18:54:28.900 回答
3

Any function or variable you access without an owning object (ex: document.getElementById) will access the property from window.

So getElementById is actually window.getElementById, which isn't natively defined (unless you defined it before (ex: getElementById = document.getElementById).

于 2009-05-12T18:54:30.257 回答
1

您应该只使用document.getElementById(即使我建议使用原型或 jquery 之类的库来使用 $ 符号)。

如果您能够单独使用 getElementById,那只是因为您使用的浏览器正在使用某种技巧来使其工作,但正确的方法是使用文档变量。

于 2009-05-12T18:52:06.953 回答
1

You should use the full document.getElementById(). If you find that too verbose, you could use jQuery:

$('#' + id)

or you could create an alias at the top of your script:

var byID = document.getElementById;
于 2009-05-12T18:54:00.367 回答
0

The correct way is indeed document.getElementById().

The reason (speculation) it might work by itself is that depending on where you use it the current context may in fact be the document object, thus inexplicitly resulting in document.getElementById().

于 2009-05-12T18:54:41.770 回答
0

我真的不知道如何解释它,但它是因为 getElementById() 在页面的 html 结构中找到了一个元素。一些浏览器知道默认情况下您要搜索文档,但其他浏览器需要额外的指导,因此需要文档。

于 2009-05-12T18:52:30.617 回答