首页 文章

jQuery mouseenter / mouseleave html() - 交换问题

提问于
浏览
4

我有以下Javascript / jQuery函数:

function addEventHandler(){

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

}

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

alt text

任何想法如何确保每个div在mouseleave上获得“Out”值?谢谢!

UPDATE: Real code excerpt

由于我的实际功能不像上面的例子那么简单,我在这里包含了真实函数的确切代码:

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 .

real problem 是当我将指针移动到另一个div时,许多div保留其员工编号 . 换句话说: mouseleave 事件不会在所有div上执行 .

Live example: http://jsfiddle.net/N9YAu/4/

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

3 回答

  • 0

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

    您应该在脚本开头存储一次原始内容,并为每个项目分别存储它们 . 我've done this in followign example using jQuery' s data 功能:http://jsfiddle.net/N9YAu/5/

    注意,我用一个 hover 绑定替换了你单独的 mouseenter / mouseleave 绑定 . 它's probably the same in the end, but it'是"proper way"这样做 .

  • 2

    我无法重现这个问题:

    http://www.jsfiddle.net/N9YAu/1/

    它也发生在你身上吗?

  • 0

    这些div中的任何一个是否可以嵌套在HTML中的其他div中?

    我想也许它可能与鼠标指针进入顶级div有关,然后在进入其他部分时没有“离开”因为它们是顶级的孩子(即使它们已被绝对定位) .

相关问题