1.前言
很多時候,頁面的dom元素是動態添加的,而我們不知道具體是哪段js代碼在操作這個dom元素,所以需要進行斷點,對相應的dom元素進行斷點監聽,這樣才能找出相關的js代碼。
在瀏覽器的調試工具中,切到elements一欄,右鍵想要操作的dom元素,在彈出的菜單中選中 "Break on",會彈出三個子選項:
subtree modifications:當此dom元素子節點發生變化時觸發斷點
Attribute modifications:當此dom元素屬性發生變化時觸發斷點
node removal:當此dom元素被移除時觸發斷點
2.監聽dom元素子節點的改變,為其設置斷點
選中subtree modifications即可
這個改變包括 添加修改子元素/添加子元素/移除子元素/修改文本節點
<div id="box">
<button onclick="changeMsg()" class="btn btn-primary">點擊改變H3的內容</button>
<button onclick="addH2()" class="btn btn-primary">添加h2標簽</button>
<button onclick="removeH3()" class="btn btn-primary">刪除h3標簽</button>
<h3>我是H3</h3>
</div>
在這個例子中,為div#box元素設置html斷點,一旦子節點發生改變,程序都會中斷執行
此時上面的3個按鈕,點擊時都會觸發斷點,並跳轉到相應的代碼位置
3.監聽dom元素屬性變化,為其設置斷點
選中Attribute modifications即可
屬性的修改/添加/移除都會觸發斷點
<BODY>
<div id="box" title="我是title">
<button onclick="changeAttr()" class="btn btn-primary">點擊改變div#box的title屬性</button>
<button onclick="addAttr()" class="btn btn-primary">添加class屬性</button>
<button onclick="removeAttr()" class="btn btn-primary">刪除title屬性</button>
<h3>我是H3</h3>
</div>
</BODY>
<script>
function changeAttr() {
document.querySelector("#box").setAttribute('title','新的title')
}
function addAttr() {
document.querySelector("#box").setAttribute('class','newClass')
}
function removeAttr() {
document.querySelector("#box").removeAttribute('title')
}
</script>
依次點擊3個按鈕,程序會中斷並跳轉到相應的位置
document.querySelector("#box").setAttribute('title','新的title')
document.querySelector("#box").setAttribute('class','newClass')
document.querySelector("#box").removeAttribute('title')
4.dom元素被移除時觸發斷點
給h3標簽設置斷點,在其被移除時觸發斷點
<div id="box" title="我是title">
<button onclick="removeH3()" class="btn btn-primary">刪除h3標簽</button>
<h3>我是H3</h3>
</div>
function removeH3() {
var h3 = document.querySelector("h3")
document.querySelector("#box").removeChild(h3)
}
點擊按鈕移除h3標簽時,程序中斷並跳轉到相應的位置
document.querySelector("#box").removeChild(h3)