關(guān)于調(diào)試
話說一個程序員的調(diào)試能力可體現(xiàn)出他的整體素質(zhì)。所以我要養(yǎng)成好的調(diào)試習(xí)慣灰伟,減少在調(diào)試上花的時間峰尝。
解決問題
今天在為多個div加拖拽時發(fā)現(xiàn)無法運行程序,于是開始分析衬吆。首先在沒有看出代碼明顯錯誤的情況下我就從基本的代碼開始排查梁钾。先看控制臺是否報錯,這時我的控制報逊抡,沒有style屬性陈轿。按照以往的經(jīng)驗一般是對象的問題,于是使用alert();的方法秦忿, 先從獲取元素開始,經(jīng)排查發(fā)現(xiàn)元素獲取正確蛾娶,然后排查onmousedown 事件灯谣, 將alert放入事件末尾發(fā)現(xiàn)還是能執(zhí)行。 在排查onmousemove時發(fā)現(xiàn)alert已經(jīng)不執(zhí)行了蛔琅。說明果然是對象的問題胎许,因為這里寫著改Left 和top 的代碼,是用的this.style.left; 也就是說我的this用的有問題,當時我就alert(this);彈出 [object HTMLDocument] 這里的this指向document,因為我是用的document.onmousemove .所以是document事件的this罗售。所以要想代碼執(zhí)行起來必須解決this的問題辜窑。 一開始我就想能不能將div循環(huán)里aDiv[i]放到這里來,試了一下結(jié)果不行寨躁,然后機開始想辦法將onmousedown的this如何用到onmousemove來穆碎。 這是想到可以定義一個變量因為onmousemove是onmousedown子函數(shù)所以在副函數(shù)定義變量子函數(shù)是可以獲取的, 這就是閉包职恳。于是我就定義了 _this = this . onmousemove 里就用_this 所禀,結(jié)果就可以運行了。 代碼如下:
window.onload = function () {
var aDiv = document.body.getElementsByTagName('div');
for (var i = 0; i < aDiv.length; i++){
aDiv[i].onmousedown = function(ev) {
var oEvent = ev || event;
var disX = oEvent.clientX - this.offsetLeft;
var disY = oEvent.clientY - this.offsetTop;
var _this = this; // 定義一個變量來接收 這里的this
document.onmousemove = function(ev){
var oEvent = ev || event;
l = oEvent.clientX - disX;
t = oEvent.clientY - disY;
_this.style.left = l + 'px'; // 引用鼠標按下里面的this
_this.style.top = t + 'px'; // 引用鼠標按下里面的this
//alert(this); //[ object HTMLDocument]
};
document.onmouseup = function () {
document.onmousemove = document.onmouseup = null;
_this.releaseCaptrue && _this.releaseCaptrue();
};
_this.setCaptrue && _this.setCaptrue();
return false;
};
}
};
end