为什么用getElementById引用很重要? [英] Why does quoting matter with getElementById?
问题描述
我在html页中有一个dom对象:
I have a dom object like this within an html page:
<textarea id="owctl7fzk">foo</textarea>
当我尝试使用 getElementById
访问它时而不引用id,它返回 null
。
When I try to access it with getElementById
without quoting the id, it returns null
.
window.document.getElementById(owctl7fzk)
但是当我将ID放在单引号或双引号中时,它将选择对象:
but when I put the id within single or double quotes, it selects the object:
window.document.getElementById('owctl7fzk')
window.document.getElementById("owctl7fzk")
在这种情况下为什么报价很重要?通常,什么时候可以省略,什么时候不可以?
Why does the quotation matter in this case? In general, when you can you omit and when can you not?
编辑在上面显示的代码中,id是十六进制数。我以前有一个十进制数字,没有引号作为id,并且没有问题。为什么?
Edit In the code I presented above, the id is a hexatridecimal number. I previously had a decimal number without quotes as id, and it had no problem. Why was that?
推荐答案
这是因为,当ID包含在引号中时,它是一个用于标识ID属性的字符串。 ,否则将其作为变量引用。如果您正在执行 window.document.getElementById(owctl7fzk)
,则javascript正在搜索名为 owctl7fzk
的变量。如果您使用 var owctl7fzk ='owctl7fzk'
,则可以使用
It's because when the ID is within a quote, its a string that is used to identify the ID attribute, otherwise it's reference as a variable. If you are performing window.document.getElementById(owctl7fzk)
, javascript is searching for a variable named owctl7fzk
. If you used var owctl7fzk = 'owctl7fzk'
, it shall work
这篇关于为什么用getElementById引用很重要?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!