document.getElementById
、$("#id")
?? ?? DOM ???/jQuery ???? ??? ?? ? ?? ??? ??? ??????
?? ??? ??? ????:
.val()
、>.html()、.text()
) 返回 undefined
null
? ???? ?? ??? ?????. ??? ?? TypeError: null ?? '...'? ??? ? ????.
??? ?? TypeError: null? ??? ??? ? ????('...' ??)
??? ?? TypeError: null? '...' ??? ?? ? ????
??? ?? TypeError: null ??? ?? ? ????('...' ??)
?? ???? ??? ??? ????.
??? ?? TypeError: 'onclick' ??? null? ??? ? ????
??? ?? TypeError: null? 'addEventList ener' ??? ?? ? ????
??? ?? TypeError: null? 'style' ??? ?? ? ????
??: ?? ?? ??? ?? ??? ???? ?? ?????.
? ??? ??? ????? ?: getElementById
,但這同樣適用于 getElementsByTagName
, querySelector ? ?? DOM ??? ???? ??? ???????.
??? ??
??? ???? ?? ? ?? ??:
??? ID? ?? ??? ??? ???? ????. getElementById
? ??? ID? (???) HTML? ?? ?? ??? ID? ??? ?????, ??? ID? ??? ?? ????? ?? ???? ???(ID? ????? ?????!).
getElementById
,請(qǐng)確保您僅提供元素的 ID(例如 document.getElemntById("the-id “)
)。如果您使用的方法接受 CSS 選擇器(例如 querySelector
),請(qǐng)確保在 ID 之前包含 #
以表明您正在查找ID(例如,document.querySelector("#the-id")
)。您不能不將#
與getElementById
一起使用,并且必須將其與querySelector
一起使用和類似的。另請(qǐng)注意,如果 ID 中包含在 CSS 標(biāo)識(shí)符(例如 .
;包含 .
字符的 id
屬性是不好的做法,但有效),您必須使用 querySelector
(document.querySelector("#the\.id")
)) 時(shí)轉(zhuǎn)義這些內(nèi)容,但使用 getElementById
( >document.getElementById("the.id")
? ???? ??
document.getElemntById("the-id ")
)? ???? ???. CSS ???? ???? ???(?: querySelector
)? ???? ?? ID ?? #
? ???? ID( ?? ?? document.querySelector("#the-id")
)???. #
? ??? ? ??? getElementById
,
querySelector
? ?? ??? ?? ?? ???? ???. ?? ID? (?: .
; .
??? ???? id
??? ?? ????? ???), querySelector (document.querySelector("#the\.id")
)) , ??? ( >document.getElementById("the.id")
)? ?????. iframe
中(這是它自己的文檔)。當(dāng)您搜索包含 iframe
? ???? ? ??? ???? ?????. iframe
或類似文件中),您需要查看 iframe
中的文檔,而不是父文檔,也許可以通過獲取 iframe
元素并使用其 contentDocument
? ?? ?? - ?? ???? ?? - ?? ??????. ????? HTML? ??? ??? ?? ???? ?????. ?? DOM ??? HTML? ???? ?? ???? DOM ??? ?? ?? ??? ???? ?????.
?? ?? ??????:
????div
出現(xiàn)在script
之后。執(zhí)行腳本時(shí),該元素尚不存在,并且 getElementById
將返回 null
.
jQuery
?? ?? jQuery ????? ?????. ???? ??? ???? ??? ???? ?? ????? ?? jQuery? ?? ??? ?? ????.
? ?? ??? ???? ?? ????? ???? ?? ????? ???? ??? jQuery? ?? ? ?? ?????.
????? ??? ????? https://? ????? HTTPS? ?? ????? ???? ????? http://? ????? HTTP ??? ??? ? ??? ?? ? ?????.
??? ????? file://somecdn.somewhere.com...
???
getElementById
(?? ?? ??? ?? DOM ???)? ???? ?? ?????? ??? ?????, ? DOM? ?????? ?????.
?? ????? ?? DOM ?? ?? JavaScript? ????? ?? ???
????? ?? ?? body ??(
????? ??? ? ???? ??? DOM? ????.
DOM? ???? ????? ??? ?? ??? ? ??? ?? ? ????. ????? HTML ??? ??? ??? ?? ?????. ??? DOM? ???? ????? (?????) ??? ??? ? ?????. ??? ????? ?????. ????? ?? DOM? ???? ??? ??? ???? ???? ???? ??? ?? ? ?? ??? ????.
?? ???? ?????. ???? #1?