当我将事件添加到同一类差异 ID 时会出现一些错误

some bug when i add event to same class diff ID

本文关键字:ID 错误 一类 事件 添加      更新时间:2023-09-26

这个演示中有一些错误。我想将相同的事件添加到同一类但差异 ID.像这样的代码

    var self;
    var id;
    var result;
    var myArray=document.getElementsByClassName("tipDiv");
    for (var i=0;i<myArray.length;i++)
        {
            document.getElementsByClassName("tipDiv")[i].onmouseover=(function(num){
                return function() {            
                    $(this).myHoverTip("hoverDiv","");
                    }
            })(i);   
            document.getElementsByClassName("tipDiv")[i].onmouseout=(function(num){
                return function() {            
                    $(this).cleanHover("hoverDiv");
                    }
            })(i);        
        }

$.fn.myHoverTip = function(divId, value) 
   {
        var div = $("#" + divId); 
        div.css("position", "absolute");
        self = $(this); 
        id = self.attr("id");
        self.hover(function() 
            {
            div.css("display", "block");
            var p = self.position(); 
            var x = p.left + self.width();
            var docWidth = $(document).width();
            if (x > docWidth - div.width() - 20) 
                {
                x = p.left - div.width();
            }
            div.css("left", x);
            div.css("top", p.top);
                function showCustomer(str)
                {
                var xmlhttp;
                if (str=="")
                  {
                  result="";
                  return;
                  }
                if (window.XMLHttpRequest)
                  {// code for IE7+, Firefox, Chrome, Opera, Safari
                  xmlhttp=new XMLHttpRequest();
                  }
                else
                  {// code for IE6, IE5
                  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
                  }
                xmlhttp.onreadystatechange=function()
                  {
                  if (xmlhttp.readyState==4 && xmlhttp.status==200)
                    {
                    result=xmlhttp.responseText;
                    }
                  }
                xmlhttp.open("GET","getbrand.asp?q="+str,true);
                xmlhttp.send();
                div.html(id+result+myArray.length);
                }
            showCustomer(id);
            },
    function() {
        div.css("display", "none");
        div.html("");
    }
    );
 return this;
}

请帮我修复错误...它不像我想要的那样工作。 首先鼠标移到悬停上不起作用。其次得到错误的值。在第三次移动时获得正确的值。我转到下一个DIV .它将获取最后一个值。请帮助我!对不起我的英语。

首先,

您不必在forloop中再次执行document.getElementsByClassName("tipDiv")。 这已经存储在 myArray ,所以你可以只使用 myArray[i] ..

但是为什么不使用jquery和悬停功能呢? api.jquery.com/hover。有了这个,您只需选择您的课程:

$(".hoverDiv").hover(...)

我想这会让你更容易..

或者使用 jquery 中的 mouseOver 函数:http://api.jquery.com/mouseover/