document.getElementById()VS. getElementById() [英] document.getElementById() VS. getElementById()

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

问题描述

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

It is common for me to register javascript functions for certain events by doing something like:

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

我一直单独使用getElementById,换句话说,没有文档作为前缀.但是,最近当我尝试使用getElementById而不是document.getElementById时,页面中断了.为什么是这样?奇怪的是,我有一个网站,其中一个页面仅允许我使用getElementById,而另一页面却引发了javascript错误,因为如果仅执行getElementById就找不到元素,并且只有在我使用时才可以执行document.getElementById.

I've always used getElementById by itself, or in other words, sans document being prepended to it. But I'm having pages break on me lately when I try to use getElementById instead of document.getElementById. Why is this? Oddly, I have a website where one page allows me to use just getElementById, but another other page throws a javascript error because it can't find the element if I do just getElementById, and it'll only work if I do document.getElementById.

有人知道这是为什么吗?我是否应该在任何地方都使用document.getElementById,而不考虑它是否在没有文档前缀的情况下起作用?

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

可能与一页正在使用AJAX而另一页没有使用AJAX的事实有关吗?

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

推荐答案

当您使用getElementById()并且它起作用时,意味着调用它的函数正在文档的上下文中运行,即==文档.

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以避免此类错误.

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

无论如何,我什至会完全停止使用getElementById并开始使用 JQuery ,我敢肯定您永远不会抱歉.

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

如果您使用JQuery,您的代码将类似于以下内容:

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

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

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

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