本人最近做一个了一个效果,就是在页面中凡是有表格的当用鼠标移动到表格上的某一行时,这行就会变背景色,于是我做了如下效果:
function setTrBg(){
var tableNum=document.getElementsByTagName("table").length;
var oTable=document.getElementsByTagName("table");
for(i=0;i<tableNum;i++)
{
var trNum=oTable[i].getElementsByTagName("tr").length;
oTrs=oTable[i].getElementsByTagName("tr");
for(var ii=0;ii<trNum;ii++){
                   if(oTrs[ii].attachEvent()){
oTrs[ii].attachEvent("onmouseover",function(){this.style.background="#ddd"},false);
oTrs[ii].attachEvent("onmouseout",function(){this.style.background="#ddd"},false);            }
                   else{
                        oTrs[ii].addEventListener("mouserover",function(){this.style.background="#ddd"});
                        oTrs[ii].addEventListener("mouserout",function(){this.style.background="#fff"});                }
}
}
window.onload=setTrBg;
上面代码运行后提示找不到this这个对象,而用下面的方法就正常function setTrBg(){
var tableNum=document.getElementsByTagName("table").length;
var oTable=document.getElementsByTagName("table");
for(i=0;i<tableNum;i++)
{
var trNum=oTable[i].getElementsByTagName("tr").length;
oTrs=oTable[i].getElementsByTagName("tr");
for(var ii=0;ii<trNum;ii++){
oTrs[ii].onmouseover=function(){this.style.background='#ddd';};
oTrs[ii].onmouseout=function(){this.style.background='#fff';}
}
}
}window.onload=setTrBg;请高手赐教!!!!鼠标 鼠标事件 JS JS对象 函数

解决方案 »

  1.   

    IE下用attachEvent的时候,里面的this不知道指哪去了;
    function toDDD(){
        this.style.background="#ddd";
    }
    function toFFF(){
        this.style.background="#fff";
    }
    oTrs[ii].attachEvent("onmouseover",function(){
        toDDD.call(oTrs[ii]);
    });
    oTrs[ii].attachEvent("onmouseout",function(){
        toFFF.call(oTrs[ii])
    });     
      

  2.   


    如此肯定是不行的,函数里的function(){toDDD.call(oTrs[ii])} oTrs[ii]不是一个对象。
      

  3.   

    我只想说,我很无语。你自己取的oTrs,我就没把你循环写出来,你就不会用。
      

  4.   


    回答问题只是提供一个思路,lz还需要从中磋磨,不可能把代码全部写好,copy下就完了
    怎么提高?
      

  5.   

    用事件传进来的参数 不要用this
    function(e){
       e包含所有事件相关和你想要的
    }