JavaScript文檔加載模式以及元素獲取
一、文檔加載模式
1.事件三要素:事件源(觸發(fā)時(shí)間的元素);事件名稱(click點(diǎn)擊事件);事件處理程序(事件出發(fā)后要執(zhí)行的代碼函數(shù)形式)存在問(wèn)題:瀏覽器加載一個(gè)頁(yè)面的時(shí)候,是按照自上而下的順序加載的,若將script標(biāo)簽寫(xiě)到head內(nèi)部,在代碼執(zhí)行時(shí)候,頁(yè)面還沒(méi)有加載,頁(yè)面中的DOM對(duì)象也沒(méi)有加載。就會(huì)導(dǎo)致js中無(wú)法獲取頁(yè)面中的DOM對(duì)象。解決方法:onload事件,會(huì)在整個(gè)頁(yè)面加載完之后才觸發(fā),為window綁定一個(gè)onload事件,該事件對(duì)應(yīng)的響應(yīng)函數(shù)將會(huì)在頁(yè)面加載完成之后執(zhí)行,這樣可以確保我們的代碼執(zhí)行時(shí)所有的DOM對(duì)象已經(jīng)加載完了
<style> button{ width:100px; height:100px; background-color:green; margin:0 auto; font-size:30px; } </style></head><body><div></div><button id='button'>點(diǎn)擊</button><script> window.onload = function (ev) { var btn = document.getElementById('button'); btn.onclick = function (ev) { alert('成功了'); } }</script></body>
運(yùn)行顯示:
點(diǎn)擊按鈕
二、文檔頁(yè)面元素獲取
根據(jù)id、標(biāo)簽名、name、類名、選擇器獲取元素
<script> window.onload = function (ev) { var btn = document.getElementById('button'); btn.onclick = function (ev) { alert('成功了'); } } window.onload = function (ea) { var btn1 = document.getElementById('button') console.log(btn1); var btn2 = document.getElementsByClassName('button2'); console.log(btn2[0]); var btn3 = document.getElementsByTagName('button'); console.log(btn3[0]); var btn4 = document.getElementsByName('button3'); console.log(btn4[0]); var btn5 = document.querySelector('#button2'); console.log(btn5); var btn6 = document.querySelectorAll('#button1'); console.log(btn6[0]); }</script>
運(yùn)行顯示:
三、源碼:
地址:https://github.com/ruigege66/JavaScript/blob/master/D27_1_Document.html
博客園:https://www.cnblogs.com/ruigege0000/
CSDN:https://blog.csdn.net/weixin_44630050?t=1
好吧啦網(wǎng):https://www.jb51.net/article/191885.htm
到此這篇關(guān)于JavaScript文檔加載模式以及元素獲取的文章就介紹到這了,更多相關(guān)JavaScript 文檔加載 元素獲取內(nèi)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. python實(shí)現(xiàn)讀取類別頻數(shù)數(shù)據(jù)畫(huà)水平條形圖案例2. python 如何停止一個(gè)死循環(huán)的線程3. Python編寫(xiě)nmap掃描工具4. 如何基于python3和Vue實(shí)現(xiàn)AES數(shù)據(jù)加密5. PHP獲取時(shí)間戳等相關(guān)函數(shù)匯總6. ASP.NET MVC前臺(tái)動(dòng)態(tài)添加文本框并在后臺(tái)使用FormCollection接收值7. 關(guān)于HTML5的img標(biāo)簽8. Java 基于UDP協(xié)議實(shí)現(xiàn)消息發(fā)送9. python 爬取嗶哩嗶哩up主信息和投稿視頻10. php5.6不能擴(kuò)展redis.so的解決方法
