English 中文(简体)
document.getElementById() VS. getElementById() 的翻译为: document.getElementById() VS. getElementById()
原标题:
  • 时间:2009-05-12 18:48:58
  •  标签:

通常我会通过类似以下方式为某些事件注册javascript函数:

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

我一直在单独使用getElementById,或者换句话说,没有在前面添加document。但是最近当我尝试使用getElementById而不是document.getElementById时,我的页面会出现错误。为什么会这样?奇怪的是,我有一个网站,其中一个页面允许我只使用getElementById,但另一个页面如果我只使用getElementById,则会引发javascript错误,并且只有使用document.getElementById才能正常工作。

Anyone know why this is? Should I be using document.getElementById everywhere, regardless of whether it works without the document prefix?

EDIT: Could it have anything to do with the fact that one page is using AJAX and the other isn t?

问题回答

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.

因此,您应始终使用document.getElementById来避免此类错误。

不管怎样,我甚至会停止使用getElementById,开始使用JQuery,我相信你绝不会后悔。

如果您使用JQuery编写代码,它的样子可能是这样的:

$("#myBtnID").click(function () { Validate($("#myTextboxID"))});

您访问的没有所有者对象的任何函数或变量(例如:document.getElementById)将从window访问该属性。

所以getElementById实际上是window.getElementById,它没有本地定义(除非你之前定义过它(例如:getElementById = document.getElementById)。

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

$( #  + id)

或者你可以在脚本的顶部创建一个别名:

var byID = document.getElementById;

你应该只使用 document.getElementById(即使我建议使用类库,如prototype或jquery,以便使用$符号)。

如果您能够独立使用getElementById函数,那只是因为您使用的浏览器进行了某种技巧来使其正常运行,但正确的方法是使用document变量。

我不是很清楚如何解释,但这是因为getElementById()在页面的HTML结构中查找元素。一些浏览器默认知道您要搜索文档,但其他浏览器需要额外的指导,因此需要document。

正确的方式确实是 document.getElementById()

它可能自行工作的原因(猜测)是,根据你使用它的位置,当前上下文实际上可能是文档对象,因此隐含地导致了document.getElementById()。





相关问题
热门标签