Javascript getElementById返回对象,getElementsByName返回none
我有以下代码Javascript getElementById返回对象,getElementsByName返回none,javascript,dom,Javascript,Dom,我有以下代码 var commentId = 1834; alert("getElementsByName:: " + typeof(document.getElementsByName("tmp_airDiff" + commentId)[0])); alert("getElementById:: " + typeof(document.getElementById("tmp_airDiff" + commentId))); 文档中没有将tmp\u airdiff 1834作为id或
var commentId = 1834;
alert("getElementsByName:: " + typeof(document.getElementsByName("tmp_airDiff" + commentId)[0]));
alert("getElementById:: " + typeof(document.getElementById("tmp_airDiff" + commentId)));
文档中没有将tmp\u airdiff 1834
作为id或名称的元素
但我得到的是:
getElementsByName:: undefined
getElementById:: object
有人能解释一下为什么
getElementById
在使用typeof
时返回object
,而文档中没有这样的对象吗?原因是document.getElementById()
在找不到具有给定ID的元素时返回null
。而typeof(null)
返回object
原因是document.getElementById()
在找不到具有给定ID的元素时返回null
。而typeof(null)
返回object
,因为
typeof null === "object"
和getElementById
返回null
是的,这很奇怪,就像NaN==“number”的类型一样,但是
在getElementsByName
的情况下,输出的是undefined
的类型,这是从数组(或类似数组的对象,此处)中访问元素时得到的类型
如果采用更适合的调试实践,您就不会陷入这种陷阱。而不是使用
alert("some name : " + typeof(someValue))
你最好:
请注意,如果在if
中进行测试,您将有一个统一的行为:
if (document.getElementsByName("tmp_airDiff" + commentId)[0]) {
// never goes there as undefined is falsy
}
if (document.getElementById("tmp_airDiff" + commentId)) {
// never goes there as null is falsy
}
你很困惑,因为
typeof null === "object"
和getElementById
返回null
是的,这很奇怪,就像NaN==“number”的类型一样,但是
在getElementsByName
的情况下,输出的是undefined
的类型,这是从数组(或类似数组的对象,此处)中访问元素时得到的类型
如果采用更适合的调试实践,您就不会陷入这种陷阱。而不是使用
alert("some name : " + typeof(someValue))
你最好:
请注意,如果在if
中进行测试,您将有一个统一的行为:
if (document.getElementsByName("tmp_airDiff" + commentId)[0]) {
// never goes there as undefined is falsy
}
if (document.getElementById("tmp_airDiff" + commentId)) {
// never goes there as null is falsy
}
如果找不到元素并且
typeof null
是对象,SimplegetElementById
将返回null
getElementsByName
返回一个集合,如果该集合为空,则任何索引都将未定义typeof undefined
未定义 SimplegetElementById
如果找不到元素并且typeof null
是对象,则返回nullgetElementsByName
返回一个集合,如果该集合为空,则任何索引都将未定义typeof undefined
未定义 getElementsByName返回undefined
的原因是它返回一个数组,而您引用的索引不存在。例如:
var array = [];
array[2320]; //undefined
array[0]; //undefined
另一方面,getElementById
在未找到元素时返回null
(它不返回空数组)。之所以返回getElementsByName
是因为它返回一个数组,而您引用的是一个不存在的索引。例如:
var array = [];
array[2320]; //undefined
array[0]; //undefined
getElementById
另一方面,当找不到元素时,返回null
(它不返回空数组)。看起来您有一个id=tmp\u airdiff 1834的元素,但没有一个具有该名称。是这样吗?表单上绝对没有名为tmp_airdiff 1834的内容。如果没有类似的名称,那么为什么您希望此代码返回与未定义不同的内容?没有HTML可显示。没有这个名称的元素。@robotron:正如你所知,typeof
不是一个函数。它后面不需要()
。如果您只需完全删除类型的
,并记录该值,您就会得到答案。看起来您有一个id=tmp\u airDiff1834的元素,但没有一个元素具有该名称。是这样吗?表单上绝对没有名为tmp_airdiff 1834的内容。如果没有类似的名称,那么为什么您希望此代码返回与未定义不同的内容?没有HTML可显示。没有这个名称的元素。@robotron:正如你所知,typeof
不是一个函数。它后面不需要()
。如果你干脆把类型的
全部去掉,只记录值,你就会得到你的答案。你让我开始使用记事本++和警报之外的其他东西。史诗按钮在哪里?!你让我开始使用记事本++和提醒之外的其他东西。史诗按钮在哪里?!