函數(shù)嵌套?
關(guān)于鼠標移動改變背景的方法:
1.慕課標準答案:
window.onload?=?function(){ Highlight(); ?} function?Highlight(){ var?tbody?=?document.getElementById('table').lastChild; trs?=?tbody.getElementsByTagName('tr');??? for(var?i?=1;i<trs.length;i++){ trs[i].onmouseover?=?function(){ this.style.backgroundColor?="#f2f2f2"; }? trs[i].onmouseout?=?function(){ this.style.backgroundColor?="#fff"; }? }?? ?} 2.大神同學(xué)的代碼: window.onload?=?function(){ ??????????var?tr=document.getElementsByTagName("tr"); ??????????for(var?i=?0;i<tr.length;i++) ??????????{ ??????????????bgcChange(tr[i]); ??????????} function?bgcChange(obj) ?????{ ????????obj.onmouseover=function(){ ????????????obj.style.backgroundColor="#f2f2f2"; ????????} ????????obj.onmouseout=function(){ ????????????obj.style.backgroundColor="#fff"; ????????} ?} 前兩種都能運行成功,有效果。 3.我的代碼: window.onload?=?function(){ ??????????hightLight(); ?} ?function?hightLight(){ ? var?tr=document.getElementsByTagName("tr"); ? for(i=0;i<tr.length;i++){ ? tr[i].onmouseover=function(){ ? ? tr[i].style.backgroundColor="red"; ? } ? tr[i].onmouseout=function(){ ? tr[i].style.backgroundColor="#fff"; ? } ? } ?} 運行報錯,說style是undefined。
不難對比得出,主要是tr[i].onmouseover=function(){ }這個函數(shù)中有所不同。1網(wǎng)站給的代碼是用了this,暫且不論,2大神給的代碼是傳遞了tr[i]進來顏色改變的函數(shù),只不過換了個名字叫obj,但是感覺實質(zhì)和我的代碼一樣的呀,為什么我的就運行不成功呢??
2016-04-16
? ?window.onload = function(){
? ? ? ? ? var tr=document.getElementsByTagName("tr");
? ? ? ? ? for(var i= 0;i<tr.length;i++)
? ? ? ? ? {
? ? ? ? ? ? ? tr[i].onmouseover=function(){
? ? ? ? ? ? this.style.backgroundColor="#f2f2f2";
? ? ? ? ? ? ? ? }
? ? ? ? ? ? tr[i].onmouseout=function(){
? ? ? ? ? ? this.style.backgroundColor="#fff";
? ? ? ? ? ? ? ? }
? ? ? ? ?}
? ? }
這樣就可以了
2016-04-15
for循環(huán)的數(shù)組下角標從零開始,最后一位是tr[i].length-1,tr[i].length是不存在的,所以會提示未定義