我具有以下Javascript / jQuery函数:

function addEventHandler(){

    $("div").mouseenter(function() {
        $(this).html("Over");
    }).mouseleave(function() {
        $(this).html("Out");
    });

}

它有效,但并非完美。 div有时会稍微重叠(不要问),并且如下图所示,它们并不总是获得“Out”值。特别是如果我将指针快速移到它们上方时,就会发生这种情况。

有什么想法可以确保每个div在mouseleave上都获得“Out”值吗?谢谢!

更新:实际代码摘录

由于我的实函数并不像上面的示例那么简单,因此我在此处包括了实函数的确切代码:
function addEventHandlers(){

    var originalContent = "";

    $(".countryspots div").mouseenter(function() {

        var thisClass = $(this).attr("class");
        var thisCountry = thisClass.split(" ");
        var thisNumber = getNumber(thisCountry[1]);

        originalContent = $(this).children("a").html();

        $(this).children("a").html("<span>" + thisNumber + "</span>");


    }).mouseleave(function() {

        $(this).children("a").html(originalContent);

    });

}

我的HTML标记是这样的:
<div class="countryspots">
    <div class="america brazil"><a href="#"><span>Brazil</span></a></div>
    <div class="america argentina"><a href="#"><span>Argentina</span></a></div>
    <div class="europe ireland"><a href="#"><span>Ireland</span></a></div>
    <div class="europe portugal"><a href="#"><span>Portugal</span></a></div>
</div>

通常的想法是,将最里面的<span>中的国家/地区名称替换为代表mouseenter上的员工编号(从getNumber();检索),然后再将其替换为mouseleave

的实际问题是,当我将指针移到另一个div时,许多div保留了其雇员编号。换句话说:并非在所有div上都执行mouseleave事件。

实时示例: http://jsfiddle.net/N9YAu/4/

希望这可以帮助。再次感谢!

最佳答案

您的问题是,对于一个您只有一个变量来存储所有项目的“原始内容”,而且mouseenter处理程序也可以在mouseleave处理程序之前第二次调用,从而导致值“原始内容”变量被覆盖悬停内容。

您应该在脚本开始时存储一次原始内容,并针对每个项目分别存储它们。我已经在下面的示例中使用jQuery的data函数做到了这一点:http://jsfiddle.net/N9YAu/5/

注意,我用一个mouseenter绑定(bind)替换了单独的mouseleave / hover绑定(bind)。最后可能是一样的,但这是“正确的方法”。

关于javascript - jQuery mouseenter/mouseleave html()-swap问题,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4283674/

10-09 20:39
查看更多